Soft BevelBorder

Friday, July 31st, 2009

import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
import javax.swing.border.SoftBevelBorder;

public class ASoftBevelBorder {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Soft Bevel Borders");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Border raisedBorder = new SoftBevelBorder(SoftBevelBorder.RAISED);
    Border loweredBorder = new SoftBevelBorder(SoftBevelBorder.LOWERED);
    JButton raisedButton = new JButton("Raised");
    raisedButton.setBorder(raisedBorder);
    JButton loweredButton = new JButton("Lowered");
    loweredButton.setBorder(loweredBorder);
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new GridLayout(1, 2));
    contentPane.add(raisedButton);
    contentPane.add(loweredButton);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}

           
       

Demonstrate Menus and the MenuBar class

Sunday, July 26th, 2009

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS “AS IS”
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun’s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun’s, and James Gosling’s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

import java.awt.CheckboxMenuItem;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/**
 * Demonstrate Menus and the MenuBar class/MenuContainer interface
 * 
 * This version uses 1.1 action handling and MenuShortcut. The action handling
 * is incomplete; realistically, each MenuItem would have its own, task-specific
 * ActionListener; this would handle the MenuShortcuts and the CheckboxMenuItems
 * correctly.
 * 
 * @author Ian Darwin
 */
public class AnotherMenuDemo extends Frame implements ActionListener, ItemListener {
  MenuBar mb;

  /** File, Options, Help */
  Menu fm, om, hm;

  /** Options Sub-Menu */
  Menu opSubm;

  /** The MenuItem for exiting. */
  MenuItem exitItem;

  /** An option that can be on or off. */
  CheckboxMenuItem cb;

  // Constructor
  AnotherMenuDemo(String s) {
    super("MenuDemo: " + s);

    Container cp = this;
    cp.setLayout(new FlowLayout());

    mb = new MenuBar();
    setMenuBar(mb); // Frame implements MenuContainer

    MenuItem mi;
    // The File Menu…
    fm = new Menu("File");
    fm.add(mi = new MenuItem("Open", new MenuShortcut(‘O’)));
    mi.addActionListener(this);
    fm.add(mi = new MenuItem("Close", new MenuShortcut(‘W’)));
    mi.addActionListener(this);
    fm.addSeparator();
    fm.add(mi = new MenuItem("Print", new MenuShortcut(‘P’)));
    mi.addActionListener(this);
    fm.addSeparator();
    fm.add(mi = new MenuItem("Exit", new MenuShortcut(‘Q’)));
    exitItem = mi; // save for action handler
    mi.addActionListener(this);
    mb.add(fm);

    // The Options Menu…
    om = new Menu("Options");
    cb = new CheckboxMenuItem("AutoSave");
    cb.setState(true);
    cb.addItemListener(this);
    om.add(cb);
    opSubm = new Menu("SubOptions");
    opSubm.add(new MenuItem("Alpha"));
    opSubm.add(new MenuItem("Gamma"));
    opSubm.add(new MenuItem("Delta"));
    om.add(opSubm);
    mb.add(om);

    // The Help Menu…
    hm = new Menu("Help");
    hm.add(mi = new MenuItem("About"));
    mi.addActionListener(this);
    hm.add(mi = new MenuItem("Topics"));
    mi.addActionListener(this);
    mb.add(hm);
    mb.setHelpMenu(hm); // needed for portability (Motif, etc.).

    // the main window
    cp.add(new Label("Menu Demo Window", 200, 150));
    pack();
  }

  /** Handle action events. */
  public void actionPerformed(ActionEvent evt) {
    // System.out.println("Event " + evt);
    String cmd;
    if ((cmd = evt.getActionCommand()) == null)
      System.out.println("You chose a menu shortcut");
    else
      System.out.println("You chose " + cmd);
    Object cmp = evt.getSource();
    // System.out.println("Source " + cmp);
    if (cmp == exitItem)
      System.exit(0);
  }

  /** The CheckBoxMenuItems send a different message */
  public void itemStateChanged(ItemEvent e) {
    System.out.println("AutoSave is set " + cb.getState());
  }

  public static void main(String[] arg) {
    new MenuDemo("Testing 1 2 3…").setVisible(true);
  }
}

           
       

Internationalized Graphical User Interfaces: unicode cut and paste

Sunday, July 19th, 2009

/*
Java Internationalization
By Andy Deitsch, David Czarnecki

ISBN: 0-596-00019-7
O’Reilly
*/
/*import java.io.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import javax.swing.*;

public class CutAndPasteDemo extends JFrame implements ClipboardOwner {

  private static String TEMPFILE = "CUTPASTE.TMP";

  String davidMessage = "David says, \"\u05E9\u05DC\u05D5\u05DD \u05E2\u05D5\u05DC\u05DD\" \n";
  String andyMessage = "Andy also says, \"\u05E9\u05DC\u05D5\u05DD \u05E2\u05D5\u05DC\u05DD\"";

  private Clipboard clipboard;

  public void lostOwnership(Clipboard clipboard, Transferable contents) {
    System.out.println("Lost clipboard ownership");
  }

  JTextArea textArea1;
  JTextArea textArea2;

  public CutAndPasteDemo() {
    super("Cut And Paste Demonstration");

    clipboard = getToolkit().getSystemClipboard();

    GraphicsEnvironment.getLocalGraphicsEnvironment();
    Font font = new Font("LucidaSans", Font.PLAIN, 15);
    textArea1 = new JTextArea(davidMessage + andyMessage, 5, 25);
    textArea2 = new JTextArea("<Paste text here>", 5, 25);
    textArea1.setFont(font);
    textArea2.setFont(font);

    JPanel jPanel = new JPanel();
    JMenuBar jMenuBar = new JMenuBar();
    JMenuItem cutItem = new JMenuItem("Cut");
    JMenuItem pasteItem = new JMenuItem("Paste");
    JMenu jMenu = new JMenu("Edit");
    jMenu.add(cutItem);
    jMenu.add(pasteItem);

    cutItem.addActionListener(new CutActionListener());
    pasteItem.addActionListener(new PasteActionListener());

    jMenuBar.add(jMenu);
    jPanel.add(jMenuBar);

    jPanel.setLayout(new BoxLayout(jPanel,BoxLayout.Y_AXIS));
    jPanel.add(textArea1);
    jPanel.add(Box.createRigidArea(new Dimension(0,10)));
    jPanel.add(textArea2);

    getContentPane().add(jPanel, BorderLayout.CENTER);
  }

  class CutActionListener implements ActionListener {

    public void actionPerformed (ActionEvent event) {
      try {
        if (textArea1.getSelectedText() != null) {
          BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(TEMPFILE), "UTF8"));
          bw.write(textArea1.getSelectedText());
          bw.close();
          textArea1.replaceSelection("");
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  class PasteActionListener implements ActionListener {

    public void actionPerformed (ActionEvent event) {
      try {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(TEMPFILE), "UTF8"));
        StringBuffer text = new StringBuffer();
        String tempString;
        while ((tempString = br.readLine()) != null) {
          text.append(tempString);
        }
        br.close();
        textArea2.replaceSelection(text.toString());
      } catch (Exception e) {
      }
    }
  }

  public static void main(String[] args) {
    JFrame frame = new CutAndPasteDemo();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {System.exit(0);}
    });

    frame.pack();
    frame.setVisible(true);
  }
}
*/

import java.io.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import javax.swing.*;

public class CutAndPasteDemo extends JFrame implements ClipboardOwner {

  private static String TEMPFILE = "CUTPASTE.TMP";

  String davidMessage = "David says, \"\u05E9\u05DC\u05D5\u05DD" +
      "\u05E2\u05D5\u05DC\u05DD\" \n";
  String andyMessage = "Andy also says, \"\u05E9\u05DC\u05D5\u05DD" +
      "\u05E2\u05D5\u05DC\u05DD\"";

  private Clipboard clipboard;

  public void lostOwnership(Clipboard clipboard, Transferable contents) {
    System.out.println("Lost clipboard ownership");
  }

  JTextArea textArea1;
  JTextArea textArea2;

  public CutAndPasteDemo() {
    super("Cut And Paste Demonstration");

    clipboard = getToolkit().getSystemClipboard();

    GraphicsEnvironment.getLocalGraphicsEnvironment();
    Font font = new Font("LucidaSans", Font.PLAIN, 15);
    textArea1 = new JTextArea(davidMessage + andyMessage, 5, 25);
    textArea2 = new JTextArea("<Paste text here>", 5, 25);
    textArea1.setFont(font);
    textArea2.setFont(font);

    JPanel jPanel = new JPanel();
    JMenuBar jMenuBar = new JMenuBar();
    JMenuItem cutItem = new JMenuItem("Cut");
    JMenuItem pasteItem = new JMenuItem("Paste");
    JMenu jMenu = new JMenu("Edit");
    jMenu.add(cutItem);
    jMenu.add(pasteItem);

    cutItem.addActionListener(new CutActionListener());
    pasteItem.addActionListener(new PasteActionListener());

    jMenuBar.add(jMenu);
    jPanel.add(jMenuBar);

    jPanel.setLayout(new BoxLayout(jPanel,BoxLayout.Y_AXIS));
    jPanel.add(textArea1);
    jPanel.add(Box.createRigidArea(new Dimension(0,10)));
    jPanel.add(textArea2);

    getContentPane().add(jPanel, BorderLayout.CENTER);
  }

  class CutActionListener implements ActionListener {

    public void actionPerformed (ActionEvent event) {
      try {
        if (textArea1.getSelectedText() != null) {
          BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new
              FileOutputStream(TEMPFILE), "UTF8"));
          bw.write(textArea1.getSelectedText());
          bw.close();
          textArea1.replaceSelection("");
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  class PasteActionListener implements ActionListener {

    public void actionPerformed (ActionEvent event) {
      try {
        BufferedReader br = new BufferedReader(new InputStreamReader(new
            FileInputStream(TEMPFILE), "UTF8"));
        StringBuffer text = new StringBuffer();
        String tempString;
        while ((tempString = br.readLine()) != null) {
          text.append(tempString);
        }
        br.close();
        textArea2.replaceSelection(text.toString());
      } catch (Exception e) {
      }
    }
  }

  public static void main(String[] args) {
    JFrame frame = new CutAndPasteDemo();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {System.exit(0);}
    });

    frame.pack();
    frame.setVisible(true);
  }
}

           
       

ColumnLayout

Sunday, July 19th, 2009

/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.com/javaexamples2.
 */

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import java.awt.Insets;
import java.awt.LayoutManager2;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * This LayoutManager arranges the components into a column. Components are
 * always given their preferred size.
 * 
 * When you create a ColumnLayout, you may specify four values: margin_height –
 * how much space to leave on top and bottom margin_width – how much space to
 * leave on left and right spacing – how much vertical space to leave between
 * items alignment – the horizontal position of the components:
 * ColumnLayout.LEFT – left-justify the components ColumnLayout.CENTER –
 * horizontally center the components ColumnLayout.RIGHT – right-justify the
 * components
 * 
 * You never call the methods of a ColumnLayout object. Just create one and make
 * it the layout manager for your container by passing it to the addLayout()
 * method of the Container object.
 */
public class ColumnLayout implements LayoutManager2 {
  protected int margin_height;

  protected int margin_width;

  protected int spacing;

  protected int alignment;

  // Constants for the alignment argument to the constructor.
  public static final int LEFT = 0;

  public static final int CENTER = 1;

  public static final int RIGHT = 2;

  /** The constructor. See comment above for meanings of these arguments */
  public ColumnLayout(int margin_height, int margin_width, int spacing,
      int alignment) {
    this.margin_height = margin_height;
    this.margin_width = margin_width;
    this.spacing = spacing;
    this.alignment = alignment;
  }

  /**
   * A default constructor that creates a ColumnLayout using 5-pixel margin
   * width and height, 5-pixel spacing, and left alignment
   */
  public ColumnLayout() {
    this(5, 5, 5, LEFT);
  }

  /**
   * The method that actually performs the layout. Called by the Container
   */
  public void layoutContainer(Container parent) {
    Insets insets = parent.getInsets();
    Dimension parent_size = parent.getSize();
    Component kid;
    int nkids = parent.getComponentCount();
    int x0 = insets.left + margin_width; // The base X position
    int x;
    int y = insets.top + margin_height; // Start at the top of the column

    for (int i = 0; i < nkids; i++) { // Loop through the kids
      kid = parent.getComponent(i); // Get the kid
      if (!kid.isVisible())
        continue; // Skip hidden ones
      Dimension pref = kid.getPreferredSize(); // How big is it?
      switch (alignment) { // Compute X coordinate
      default:
      case LEFT:
        x = x0;
        break;
      case CENTER:
        x = (parent_size.width - pref.width) / 2;
        break;
      case RIGHT:
        x = parent_size.width - insets.right - margin_width
            - pref.width;
        break;
      }
      // Set the size and position of this kid
      kid.setBounds(x, y, pref.width, pref.height);
      y += pref.height + spacing; // Get Y position of the next one
    }
  }

  /** The Container calls this to find out how big the layout should to be */
  public Dimension preferredLayoutSize(Container parent) {
    return layoutSize(parent, 1);
  }

  /** The Container calls this to find out how big the layout must be */
  public Dimension minimumLayoutSize(Container parent) {
    return layoutSize(parent, 2);
  }

  /** The Container calls this to find out how big the layout can be */
  public Dimension maximumLayoutSize(Container parent) {
    return layoutSize(parent, 3);
  }

  // Compute min, max, or preferred size of all the visible children
  protected Dimension layoutSize(Container parent, int sizetype) {
    int nkids = parent.getComponentCount();
    Dimension size = new Dimension(0, 0);
    Insets insets = parent.getInsets();
    int num_visible_kids = 0;

    // Compute maximum width and total height of all visible kids
    for (int i = 0; i < nkids; i++) {
      Component kid = parent.getComponent(i);
      Dimension d;
      if (!kid.isVisible())
        continue;
      num_visible_kids++;
      if (sizetype == 1)
        d = kid.getPreferredSize();
      else if (sizetype == 2)
        d = kid.getMinimumSize();
      else
        d = kid.getMaximumSize();
      if (d.width > size.width)
        size.width = d.width;
      size.height += d.height;
    }

    // Now add in margins and stuff
    size.width += insets.left + insets.right + 2 * margin_width;
    size.height += insets.top + insets.bottom + 2 * margin_height;
    if (num_visible_kids > 1)
      size.height += (num_visible_kids - 1) * spacing;
    return size;
  }

  // Other LayoutManager(2) methods that are unused by this class
  public void addLayoutComponent(String constraint, Component comp) {
  }

  public void addLayoutComponent(Component comp, Object constraint) {
  }

  public void removeLayoutComponent(Component comp) {
  }

  public void invalidateLayout(Container parent) {
  }

  public float getLayoutAlignmentX(Container parent) {
    return 0.5f;
  }

  public float getLayoutAlignmentY(Container parent) {
    return 0.5f;
  }
}

class ColumnLayoutPane extends JPanel {
  public ColumnLayoutPane() {
    // Get rid of the default layout manager.
    // We’ll arrange the components ourselves.
    this.setLayout(new ColumnLayout(5, 5, 10, ColumnLayout.RIGHT));

    // Create some buttons and set their sizes and positions explicitly
    for (int i = 0; i < 6; i++) {
      int pointsize = 8 + i * 2;
      JButton b = new JButton("Point size " + pointsize);
      b.setFont(new Font("helvetica", Font.BOLD, pointsize));
      this.add(b);
    }
  }
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    f.setContentPane(new ColumnLayoutPane());
    f.pack();
    f.setVisible(true);
  }

  
}

           
       

A quick application to show a simple JLabel

Sunday, July 19th, 2009

//A quick application to show a simple JLabel.

import javax.swing.JFrame;
import javax.swing.JLabel;

public class SimpleJLabelExample {
  public static void main(String[] args) {
    JLabel label = new JLabel("A Very Simple Text Label");

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(label);
    frame.pack();
    frame.setVisible(true);
  }
}