Home  Listings  By Name  By Subject  Email  www.tomswan.com  Help 

Java 2 Just Click! Solutions

Chapter 22 Listings

© 2001 by Tom Swan. All rights reserved. Updated: 6/4/01 12:20:54 PM

Return to Listings page
Switch to Solutions by name page
Switch to Solutions by subject page


Listing 22-1 ButtonIcon/ButtonIcon.java Page 464

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class ButtonIcon extends JFrame {
006: 
007: // Constructor does all the setup work
008:  public ButtonIcon() {
009: 
010:   // Select local system look and feel
011:   try {
012:    UIManager.setLookAndFeel(
013:     UIManager.getSystemLookAndFeelClassName());
014:   } catch (Exception e) { }
015: 
016:   // End program when window closes
017:   addWindowListener(new WindowAdapter() {
018:    public void windowClosing(WindowEvent e) {
019:     System.exit(0);
020:    }
021:   });
022: 
023:   ImageIcon prevIcon = new ImageIcon("lefthand.gif");
024:   JButton prevButton = new JButton("Prev", prevIcon);
025:   prevButton.setToolTipText("Move to the previous page");
026:   ImageIcon nextIcon = new ImageIcon("righthand.gif");
027:   JButton nextButton = new JButton("Next", nextIcon);
028:   nextButton.setToolTipText("Move to the next page");
029: 
030:   Container content = getContentPane();
031:   content.setLayout(new FlowLayout());
032:   content.add(prevButton);
033:   content.add(nextButton);
034:  }
035: 
036:  public static void main(String[] args) {
037:   ButtonIcon app = new ButtonIcon();
038:   app.setTitle("Button Icon Demo");
039:   app.setSize(320, 120);
040:   app.show();
041:  }
042: }
Return to top

Listing 22-2 ToggleDemo/ToggleDemo.java Page 466

Return to top
001: import javax.swing.*;
002: import javax.swing.event.*;
003: import java.awt.*;
004: import java.awt.event.*;
005: 
006: public class ToggleDemo extends JFrame {
007: 
008:   ImageIcon bulbOnIcon;
009:   ImageIcon bulbOffIcon;
010:   JToggleButton onOffButton;
011: 
012: // Constructor does all the setup work
013:  public ToggleDemo() {
014: 
015:   // Select local system look and feel
016:   try {
017:    UIManager.setLookAndFeel(
018:     UIManager.getSystemLookAndFeelClassName());
019:   } catch (Exception e) { }
020: 
021:   // End program when window closes
022:   addWindowListener(new WindowAdapter() {
023:    public void windowClosing(WindowEvent e) {
024:     System.exit(0);
025:    }
026:   });
027: 
028:   bulbOnIcon = new ImageIcon("bulbon.gif");
029:   bulbOffIcon = new ImageIcon("bulboff.gif");
030:   onOffButton = new JToggleButton("Off", bulbOffIcon);
031:   onOffButton.addChangeListener(new ChangeListener() {
032:    public void stateChanged(ChangeEvent e) {
033:     if (onOffButton.isSelected()) {
034:      onOffButton.setIcon(bulbOnIcon);
035:      onOffButton.setText("On");
036:     } else {
037:      onOffButton.setIcon(bulbOffIcon);
038:      onOffButton.setText("Off");
039:     }
040:    }
041:   });
042: 
043:   Container content = getContentPane();
044:   content.setLayout(new FlowLayout());
045:   content.add(onOffButton);
046:  }
047: 
048:  public static void main(String[] args) {
049:   ToggleDemo app = new ToggleDemo();
050:   app.setTitle("Toggle Button Demonstration");
051:   app.setSize(320, 120);
052:   app.show();
053:  }
054: }
Return to top

Listing 22-3 ButtonDemo/ButtonDemo.java Page 469

Return to top
001: import javax.swing.*;
002: import javax.swing.border.*;
003: import javax.swing.event.*;
004: import java.awt.*;
005: import java.awt.event.*;
006: 
007: // The main program class
008: public class ButtonDemo 
009:  extends JFrame implements ActionListener {
010: 
011:  // GUI objects displayed in the frame window
012:  ButtonGroup group;            // Groups radio buttons
013:  JRadioButton redButton;       // First radio button
014:  JRadioButton whiteButton;     // Second radio button
015:  JRadioButton blueButton;      // Third radio button
016:  JPanel colorBox;              // Displays selected color
017:  JCheckBox showColorsButton;   // First check box
018:  JCheckBox exitOnCloseButton;  // Second check box
019:  JButton exitButton;           // Plain button
020: 
021: // Constructor initializes the GUI objects and panels
022:  public ButtonDemo() {
023: 
024:   // Select local system look and feel
025:   try {
026:    UIManager.setLookAndFeel(
027:     UIManager.getSystemLookAndFeelClassName());
028: //    UIManager.getCrossPlatformLookAndFeelClassName());
029:   } catch (Exception e) { }
030: 
031:   // End program when window closes
032:   addWindowListener(new WindowAdapter() {
033:    public void windowClosing(WindowEvent e) {
034:     System.exit(0);
035:    }
036:   });
037: 
038:   //==========================================================
039:   // Radio button panel and GUI objects
040:   //==========================================================
041: 
042:   // Create radio button panel and an inner pane
043:   // to help display the GUI objects neatly
044:   JPanel radioPane = new JPanel();
045:   JPanel innerRadioPane = new JPanel();
046:   radioPane.setBorder(
047:    BorderFactory.createBevelBorder(BevelBorder.RAISED));
048:   innerRadioPane.setLayout(
049:    new BoxLayout(innerRadioPane, BoxLayout.Y_AXIS));
050:   innerRadioPane.setBorder(
051:    BorderFactory.createEmptyBorder(10, 10, 10, 10));
052: 
053:   // Construct the radio group and its buttons
054:   // All button events go to the program's ActionListener
055:   group       = new ButtonGroup();
056:   redButton   = new JRadioButton("Red  ");
057:   whiteButton = new JRadioButton("White");
058:   blueButton  = new JRadioButton("Blue ");
059:   whiteButton.setSelected(true); // Select one button
060:   redButton.addActionListener(this);  // See ActionPerformed()
061:   whiteButton.addActionListener(this);
062:   blueButton.addActionListener(this);
063:   group.add(redButton);   // The group ensures that when one
064:   group.add(whiteButton); // button is selected, the previously
065:   group.add(blueButton);  // selected button is turned off
066: 
067:   // Construct a small panel for displaying the selected color
068:   colorBox = new JPanel();
069:   colorBox.setBackground(Color.white);
070:   colorBox.setPreferredSize(new Dimension(50, 50));
071: 
072:   // Add the GUI objects to the inner radio pane
073:   innerRadioPane.add(redButton);
074:   innerRadioPane.add(whiteButton);
075:   innerRadioPane.add(blueButton);
076:   innerRadioPane.add(
077:    Box.createRigidArea(new Dimension(0, 25)));  // Spacer
078:   innerRadioPane.add(colorBox);
079: 
080:   // Add the inner pane to the raised radio panel (left side)
081:   radioPane.add(innerRadioPane);
082: 
083:   //==========================================================
084:   // Check box panel and GUI objects
085:   //==========================================================
086: 
087:   // Create check box panel and an inner panel
088:   // for a neat appearance
089:   JPanel checkPane = new JPanel();
090:   JPanel innerCheckPane = new JPanel();
091:   checkPane.setBorder(
092:    BorderFactory.createBevelBorder(BevelBorder.RAISED));
093:   innerCheckPane.setLayout(
094:    new BoxLayout(innerCheckPane, BoxLayout.Y_AXIS));
095:   innerCheckPane.setBorder(
096:    BorderFactory.createEmptyBorder(10, 10, 10, 10));
097: 
098:   // Create the "show colors" check box object and
099:   // enable or disable the color radio buttons
100:   showColorsButton = new JCheckBox("Show colors");
101:   showColorsButton.setSelected(true);
102:   showColorsButton.addChangeListener(new ChangeListener() {
103:    public void stateChanged(ChangeEvent e) {
104:     boolean t = showColorsButton.isSelected();
105:     redButton.setEnabled(t);   // Enable or disable all 
106:     whiteButton.setEnabled(t); // radio buttons depending on
107:     blueButton.setEnabled(t);  // state of check box
108:    }
109:   });
110: 
111:   // Create the "exit on close" check box object and
112:   // enable or disable the Exit Program button
113:   exitOnCloseButton = new JCheckBox("Exit on close");
114:   exitOnCloseButton.addChangeListener(new ChangeListener() {
115:    public void stateChanged(ChangeEvent e) {
116:     boolean t = exitOnCloseButton.isSelected();
117:     exitButton.setEnabled(t);
118:    }
119:   });
120: 
121:   // Create the plain "Exit Program" button
122:   // and its action event listener
123:   exitButton = new JButton("Exit Program");
124:   exitButton.setEnabled(false);  // Initially disabled
125:   exitButton.addActionListener(new ActionListener() {
126:    public void actionPerformed(ActionEvent e) {
127:      System.exit(0);
128:    }
129:   });
130: 
131:   // Add the buttons to the inner pane
132:   innerCheckPane.add(showColorsButton);
133:   innerCheckPane.add(exitOnCloseButton);
134:   innerCheckPane.add(
135:    Box.createRigidArea(new Dimension(0, 50)));
136:   innerCheckPane.add(exitButton);
137: 
138:   // Add the inner pane to the raised check box panel
139:   checkPane.add(innerCheckPane);
140: 
141:   // Add the panels and GUI objects to the frame's content pane
142:   Container content = getContentPane();
143:   content.setLayout(new GridLayout(1, 3, 2, 2));
144:   content.add(radioPane);
145:   content.add(checkPane);
146:  }
147: 
148:  // Change the colorBox background color when user
149:  // selects a radio button.
150:  public void actionPerformed(ActionEvent e) {
151:   Color c;
152:   if (redButton.isSelected()) c = Color.red;
153:   else if (whiteButton.isSelected()) c = Color.white;
154:   else c = Color.blue;
155:   colorBox.setBackground(c);
156:  }
157: 
158:  // Main program simply constructs the ButtonDemo 
159:  // application object, and then sizes and shows the window
160:  public static void main(String[] args) {
161:   ButtonDemo app = new ButtonDemo();
162:   app.setTitle("Button and Check Box Demo");
163:   app.setSize(320, 240);
164:   app.show();
165:  }
166: }
Return to top

Listing 22-4 MessageDemo/MessageDemo.java Page 475

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class MessageDemo 
006:  extends JFrame implements ActionListener {
007: 
008:   final int WARNING = JOptionPane.WARNING_MESSAGE;
009:   final int ERROR = JOptionPane.ERROR_MESSAGE;
010:   final int PLAIN = JOptionPane.PLAIN_MESSAGE;
011:   final int INFO = JOptionPane.INFORMATION_MESSAGE;
012: 
013:   JButton defaultButton;
014:   JButton warningButton;
015:   JButton errorButton;
016:   JButton plainButton;
017:   JButton infoButton;
018: 
019:  public void showMessage(String s, int msgType) {
020:   if (msgType < 0)
021:    JOptionPane.showMessageDialog(this, s);
022:   else
023:    JOptionPane.showMessageDialog(this, s, "Message", msgType);
024:  }
025: 
026: // Constructor does all the setup work
027:  public MessageDemo() {
028: 
029:   // Select local system look and feel
030:   try {
031:    UIManager.setLookAndFeel(
032:     UIManager.getSystemLookAndFeelClassName());
033:   } catch (Exception e) { }
034: 
035:   // End program when window closes
036:   addWindowListener(new WindowAdapter() {
037:    public void windowClosing(WindowEvent e) {
038:     System.exit(0);
039:    }
040:   });
041: 
042:   defaultButton = new JButton("Default");
043:   warningButton = new JButton("Warning");
044:   errorButton = new JButton("Error");
045:   plainButton = new JButton("Plain");
046:   infoButton = new JButton("Info");
047:   defaultButton.addActionListener(this);
048:   warningButton.addActionListener(this);
049:   errorButton.addActionListener(this);
050:   plainButton.addActionListener(this);
051:   infoButton.addActionListener(this);
052: 
053:   Container content = getContentPane();
054:   content.setLayout(new GridLayout(3, 2, 2, 2));
055:   content.add(defaultButton);
056:   content.add(warningButton);
057:   content.add(errorButton);
058:   content.add(plainButton);
059:   content.add(infoButton);
060:  }
061: 
062:  public void actionPerformed(ActionEvent e) {
063:   Object source = e.getSource();  // Which button?
064:   if (source.equals(defaultButton))
065:    showMessage("Default message dialog", -1);
066:   else if (source.equals(warningButton)) 
067:    showMessage("Warning message dialog", WARNING);
068:   else if (source.equals(errorButton))
069:    showMessage("Error message dialog", ERROR);
070:   else if (source.equals(plainButton))
071:    showMessage("Plain message dialog", PLAIN);
072:   else if (source.equals(infoButton))
073:    showMessage("Information message dialog", INFO);
074:  }
075: 
076:  public static void main(String[] args) {
077:   MessageDemo app = new MessageDemo();
078:   app.setTitle("Message Dialog Demo");
079:   app.setSize(320, 240);
080:   app.show();
081:  }
082: }
Return to top

Listing 22-5 YesNoDemo/YesNoDemo.java Page 478

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class YesNoDemo extends JFrame {
006: 
007: // Constructor does all the setup work
008:  public YesNoDemo() {
009: 
010:   // Select local system look and feel
011:   try {
012:    UIManager.setLookAndFeel(
013:     UIManager.getSystemLookAndFeelClassName());
014:   } catch (Exception e) { }
015: 
016:   // End program when window closes
017:   addWindowListener(new WindowAdapter() {
018:    public void windowClosing(WindowEvent e) {
019:     System.exit(0);
020:    }
021:   });
022: 
023:   JButton optionButton = new JButton("Click Me!");
024:   optionButton.addActionListener(new ActionListener() {
025:    public void actionPerformed(ActionEvent e) {
026:     int result = 
027:      JOptionPane.showConfirmDialog(null,
028:       "Exit this program now?",
029:       "Please answer",
030:       JOptionPane.YES_NO_OPTION);
031:     if (result == JOptionPane.YES_OPTION)
032:      System.exit(0);
033:    }   
034:   });
035: 
036:   Container content = getContentPane();
037:   content.add(optionButton);
038:  }
039: 
040:  public static void main(String[] args) {
041:   YesNoDemo app = new YesNoDemo();
042:   app.setTitle("Confirm Dialog Demonstration");
043:   app.setSize(320, 240);
044:   app.show();
045:  }
046: }
Return to top

Listing 22-6 FileDialog/FileDialog.java Page 480

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class FileDialog extends JFrame {
006: 
007:  private JFileChooser fDialog;
008:  JFrame frame;  // Reference to this frame object
009: 
010: // Constructor does all the setup work
011:  public FileDialog() {
012: 
013:   frame = this;  // So action listeners can find it
014: 
015:   // Select local system look and feel
016:   try {
017:    UIManager.setLookAndFeel(
018:     UIManager.getSystemLookAndFeelClassName());
019:   } catch (Exception e) { }
020: 
021:   // End program when window closes
022:   addWindowListener(new WindowAdapter() {
023:    public void windowClosing(WindowEvent e) {
024:     System.exit(0);
025:    }
026:   });
027: 
028:   // Construct the file chooser dialog object
029:   fDialog = new JFileChooser();
030: 
031:   // Open button displays File:Open dialog
032:   JButton openButton = new JButton("Open File Dialog");
033:   openButton.addActionListener(new ActionListener() {
034:    public void actionPerformed(ActionEvent e) {
035:     String msg;
036:     int result = fDialog.showOpenDialog(frame);
037:     if (result == JFileChooser.APPROVE_OPTION) {
038:      String fname = fDialog.getName(fDialog.getSelectedFile());
039:      frame.setTitle(fname);
040:      msg = "File Open Approved";
041:     } else 
042:      msg = "File Open Cancelled";
043:     JOptionPane.showMessageDialog(frame, msg);
044:    }
045:   });
046: 
047:   // Save button displays File:Save dialog
048:   JButton saveButton = new JButton("Save File Dialog");
049:   saveButton.addActionListener(new ActionListener() {
050:    public void actionPerformed(ActionEvent e) {
051:     String msg;
052:     int result = fDialog.showSaveDialog(frame);
053:     if (result == JFileChooser.APPROVE_OPTION) {
054:      String fname = fDialog.getName(fDialog.getSelectedFile());
055:      frame.setTitle(fname);
056:      msg = "File Save Approved";
057:     } else 
058:      msg = "File Save Cancelled";
059:     JOptionPane.showMessageDialog(frame, msg);
060:    }
061:   });
062: 
063:   // Add buttons to the frame's content pane
064:   Container content = getContentPane();
065:   content.setLayout(new GridLayout(2, 1, 2, 2));
066:   content.add(openButton);
067:   content.add(saveButton);
068:  }
069: 
070:  public static void main(String[] args) {
071:   FileDialog app = new FileDialog();
072:   app.setTitle("File Dialog Demonstration");
073:   app.setSize(320, 240);
074:   app.show();
075:  }
076: }
Return to top

Listing 22-7 ColorDemo/ColorDemo.java Page 484

Return to top
001: import javax.swing.*;
002: import javax.swing.event.*;
003: import java.awt.*;
004: import java.awt.event.*;
005: 
006: public class ColorDemo extends JFrame {
007: 
008:  private JColorChooser colorChooser;  // The Color chooser
009:  private JPanel colorBox;             // Color sample
010:  private Color selectedColor;         // Selected color
011: 
012: // Constructor does all the setup work
013:  public ColorDemo() {
014: 
015:   // Select local system look and feel
016:   try {
017:    UIManager.setLookAndFeel(
018:     UIManager.getSystemLookAndFeelClassName());
019:   } catch (Exception e) { }
020: 
021:   // End program when window closes
022:   addWindowListener(new WindowAdapter() {
023:    public void windowClosing(WindowEvent e) {
024:     System.exit(0);
025:    }
026:   });
027: 
028:   // Set current color and sample panel (top)
029:   selectedColor = Color.white;
030:   colorBox = new JPanel();
031:   colorBox.setBackground(selectedColor);
032:   colorBox.setPreferredSize(new Dimension(150, 100));
033:   colorBox.setBorder(
034:    BorderFactory.createLineBorder(Color.black));
035: 
036:   // Create color chooser and change event listener
037:   colorChooser = new JColorChooser(selectedColor);
038:   colorChooser.getSelectionModel().addChangeListener(
039:    new ChangeListener() {
040:     public void stateChanged(ChangeEvent e) {
041:      selectedColor = colorChooser.getColor();
042:      colorBox.setBackground(selectedColor);
043:     }
044:    }
045:   );
046: 
047:   // Add the sample color pane and chooser to the frame
048:   Container content = getContentPane();
049:   content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
050:   content.add(colorBox);
051:   content.add(colorChooser);
052:  }
053: 
054:  public static void main(String[] args) {
055:   ColorDemo app = new ColorDemo();
056:   app.setTitle("Color Chooser Demonstration");
057:   app.setSize(450, 400);
058:   app.show();
059:  }
060: }
Return to top

Listing 22-8 LabelDemo/LabelDemo.java Page 485

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class LabelDemo extends JFrame {
006: 
007: // Constructor does all the setup work
008:  public LabelDemo() {
009: 
010:   // Select local system look and feel
011:   try {
012:    UIManager.setLookAndFeel(
013:     UIManager.getSystemLookAndFeelClassName());
014:   } catch (Exception e) { }
015: 
016:   // End program when window closes
017:   addWindowListener(new WindowAdapter() {
018:    public void windowClosing(WindowEvent e) {
019:     System.exit(0);
020:    }
021:   });
022: 
023:   // Place components in a pane for better appearance
024:   JPanel pane = new JPanel();
025:   pane.setLayout(new GridLayout(3, 1, 2, 2));
026:   pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 0));
027: 
028:   // Create a simple label using default text
029:   JLabel titleLabel = new JLabel("Three little labels");
030: 
031:   // Add an icon image to a label
032:   ImageIcon mailIcon = new ImageIcon("mailbox.gif");
033:   JLabel mailLabel = new JLabel(mailIcon, JLabel.LEADING);
034:   mailLabel.setText("You have mail");
035: 
036:   // Use HTML to format a label's text font and size
037:   String s = ""
038:    + "Check this out!"
039:    + "";
040:   ImageIcon handIcon = new ImageIcon("righthand.gif");
041:   JLabel htmlLabel = new JLabel(s, handIcon, JLabel.CENTER);
042: 
043:   // Add components to the pane, and the pane to content layer
044:   pane.add(titleLabel);
045:   pane.add(mailLabel);
046:   pane.add(htmlLabel);
047:   getContentPane().add(pane);
048:  }
049: 
050:  public static void main(String[] args) {
051:   LabelDemo app = new LabelDemo();
052:   app.setTitle("Label Demonstration");
053:   app.setSize(320, 240);
054:   app.show();
055:  }
056: }
Return to top

Listing 22-9 Password/Password.java Page 487

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class Password 
006:  extends JFrame implements ActionListener {
007: 
008:  JTextField username;
009:  JPasswordField password;
010:  JButton logon;
011: 
012: // Constructor does all the setup work
013:  public Password() {
014: 
015:   // Select local system look and feel
016:   try {
017:    UIManager.setLookAndFeel(
018:     UIManager.getSystemLookAndFeelClassName());
019:   } catch (Exception e) { }
020: 
021:   // End program when window closes
022:   addWindowListener(new WindowAdapter() {
023:    public void windowClosing(WindowEvent e) {
024:     System.exit(0);
025:    }
026:   });
027: 
028:   // Use inner panel for a neat appearance
029:   JPanel pane = new JPanel();
030:   pane.setLayout(new GridLayout(3, 2, 2, 2));
031:   pane.setBorder(
032:    BorderFactory.createEmptyBorder(10, 10, 10, 0));
033: 
034:   username = new JTextField(16);
035:   password = new JPasswordField(16);
036:   logon = new JButton("Logon");
037:   logon.addActionListener(this);
038: 
039:   // Prevent user from resizing this JFrame
040:   setResizable(false);
041: 
042:   // Add components to the pane, and the pane to content layer
043:   pane.add(new JLabel("User name:"));
044:   pane.add(username);
045:   pane.add(new JLabel("Password:"));
046:   pane.add(password);
047:   pane.add(new JLabel("Click button to logon:"));
048:   pane.add(logon);
049:   getContentPane().add(pane);
050:  }
051: 
052:  public void actionPerformed(ActionEvent e) {
053:   Object source = e.getSource();  // Which component?
054:   if (source.equals(logon)) {
055:    // *** WARNING: SECURITY DANGER
056:    char[] ptext = password.getPassword();  // ok
057:    String s = new String(ptext);  // ???
058:    JOptionPane.showMessageDialog(this, "Password: " + s);
059:    // Erase password for safety
060:    for (int i = 0; i < ptext.length; i++)
061:     ptext[i] = 0;
062:    // *** END SECURITY DANGER
063:   }
064:  }
065: 
066:  public static void main(String[] args) {
067:   Password app = new Password();
068:   app.setTitle("Text field and password demo");
069:   app.setSize(320, 120);
070:   app.show();
071:  }
072: }
Return to top

Listing 22-10 TextDemo/TextDemo.java Page 490

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class TextDemo extends JFrame {
006: 
007: // Constructor does all the setup work
008:  public TextDemo() {
009: 
010:   // Select local system look and feel
011:   try {
012:    UIManager.setLookAndFeel(
013:     UIManager.getSystemLookAndFeelClassName());
014:   } catch (Exception e) { }
015: 
016:   // End program when window closes
017:   addWindowListener(new WindowAdapter() {
018:    public void windowClosing(WindowEvent e) {
019:     System.exit(0);
020:    }
021:   });
022: 
023:   // Use inner panel for a neat appearance
024:   JPanel pane = new JPanel();
025: 
026:   // Create text area object
027:   JTextArea theText = new JTextArea();
028:   theText.setFont(new Font("Courier", Font.PLAIN, 12));
029:   theText.setLineWrap(false);
030: 
031:   // Add a scroller to the text area object
032:   JScrollPane scroller = new JScrollPane(theText);
033:   scroller.setPreferredSize(new Dimension(300, 150));
034:   scroller.setVerticalScrollBarPolicy(
035:    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
036: 
037:   // Create a label for the text area object
038:   String s = ""
039:    + "Text area:"
040:    + "";
041:   JLabel inputLabel = new JLabel(s);
042:   inputLabel.setLabelFor(theText);
043:   inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
044: 
045:   // Add all components to the content pane
046:   pane.add(inputLabel);
047:   pane.add(scroller);
048:   getContentPane().add(pane);
049:   setResizable(false);
050:  }
051: 
052:  public static void main(String[] args) {
053:   TextDemo app = new TextDemo();
054:   app.setTitle("Text Area Demonstration");
055:   app.setSize(320, 240);
056:   app.show();
057:  }
058: }
Return to top

Listing 22-11 ListDemo/ListDemo.java Page 492

Return to top
001: import javax.swing.*;
002: import javax.swing.event.*;
003: import java.awt.*;
004: import java.awt.event.*;
005: 
006: public class ListDemo extends JFrame {
007: 
008:  private JFrame frame;  // Refers to this JFrame window
009:  private JLabel label;  // Shows current selection
010: 
011: // Constructor does all the setup work
012:  public ListDemo() {
013: 
014:   // Select local system look and feel
015:   try {
016:    UIManager.setLookAndFeel(
017:     UIManager.getSystemLookAndFeelClassName());
018:   } catch (Exception e) { }
019: 
020:   // End program when window closes
021:   addWindowListener(new WindowAdapter() {
022:    public void windowClosing(WindowEvent e) {
023:     System.exit(0);
024:    }
025:   });
026: 
027:   frame = this;  // So event handler can find our window
028: 
029:   String[] items = {
030:    "Sunday", "Monday", "Tuesday", "Wednesday",
031:    "Thursday", "Friday", "Saturday"
032:   };
033:   JList dayList = new JList(items);
034:   dayList.setSelectionMode(
035:    ListSelectionModel.SINGLE_SELECTION);
036:   dayList.setAlignmentX(Component.CENTER_ALIGNMENT);
037:   JScrollPane listScroller = new JScrollPane(dayList);
038: 
039:   // Respond to a list selection event
040:   dayList.addListSelectionListener(
041:    new ListSelectionListener() {
042:     public void valueChanged(ListSelectionEvent e) {
043:      JList list = (JList)e.getSource();
044:      if (!list.isSelectionEmpty()) {
045:       int i = list.getSelectedIndex();
046:       String s = (String)list.getModel().getElementAt(i);
047:       label.setText("Selection: " + s);
048:      }
049:     }
050:    }
051:   );
052: 
053:   label = new JLabel("Select a day");
054:   Container content = getContentPane();
055:   content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
056:   content.add(label);
057:   content.add(listScroller);
058:  }
059: 
060:  public static void main(String[] args) {
061:   ListDemo app = new ListDemo();
062:   app.setTitle("List Demonstration");
063:   app.setSize(320, 240);
064:   app.show();
065:  }
066: }
Return to top

Listing 22-12 ComboDemo/ComboDemo.java Page 496

Return to top
001: import javax.swing.*;
002: import javax.swing.event.*;
003: import java.awt.*;
004: import java.awt.event.*;
005: 
006: public class ComboDemo extends JFrame {
007: 
008:  private JFrame frame;  // Refers to this JFrame window
009:  private JLabel label;  // Shows current selection
010: 
011: // Constructor does all the setup work
012:  public ComboDemo() {
013: 
014:   // Select local system look and feel
015:   try {
016:    UIManager.setLookAndFeel(
017:     UIManager.getSystemLookAndFeelClassName());
018:   } catch (Exception e) { }
019: 
020:   // End program when window closes
021:   addWindowListener(new WindowAdapter() {
022:    public void windowClosing(WindowEvent e) {
023:     System.exit(0);
024:    }
025:   });
026: 
027:   frame = this;  // So event handler can find our window
028:   label = new JLabel("Select a month");
029: 
030:   String[] items = {
031:    "January", "February", "March", "April", "May",
032:    "June", "July", "August", "September", "October",
033:    "November", "December"
034:   };
035:   JComboBox months = new JComboBox(items);
036:   months.setSelectedIndex(0);
037:   months.setEditable(true);
038:   months.addActionListener(
039:    new ActionListener() {
040:     public void actionPerformed(ActionEvent e) {
041:      JComboBox box = (JComboBox)e.getSource();
042:      String s = (String)box.getSelectedItem();
043:      label.setText("Selection: " + s);
044:     }
045:    }
046:   );
047: 
048:   JPanel pane = new JPanel();
049:   pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
050:   pane.setBorder(
051:    BorderFactory.createEmptyBorder(20, 20, 20, 20));
052:   pane.add(label);
053:   pane.add(months);
054: 
055:   getContentPane().add(pane, BorderLayout.CENTER);
056:  }
057: 
058:  public static void main(String[] args) {
059:   ComboDemo app = new ComboDemo();
060:   app.setTitle("Combo Box Demonstration");
061:   app.setSize(320, 240);
062:   app.show();
063:  }
064: }
Return to top

Listing 22-13 PopupDemo/PopupDemo.java Page 499

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class PopupDemo 
006:  extends JFrame implements ActionListener {
007: 
008:  // This is the popup menu object
009:  protected JPopupMenu popupMenu;
010: 
011:  // These are the popup menu items
012:  protected JMenuItem openMenuItem;
013:  protected JMenuItem saveMenuItem;
014:  protected JMenuItem closeMenuItem;
015:  protected JMenuItem exitMenuItem;
016: 
017:  // Inner class pops up the menu when the proper mouse
018:  // click or release is detected for the current look and feel
019:  class PopupHandler extends MouseAdapter {
020:   public void mousePressed(MouseEvent e) {
021:    if (e.isPopupTrigger())
022:     popupMenu.show(e.getComponent(), e.getX(), e.getY());
023:   }
024:   public void mouseReleased(MouseEvent e) {
025:    if (e.isPopupTrigger())
026:     popupMenu.show(e.getComponent(), e.getX(), e.getY());
027:   }
028:  } 
029: 
030:  // Create the popup menu and its commands
031:  private void createPopupMenu() {
032:   popupMenu = new JPopupMenu();
033:   openMenuItem = new JMenuItem("Open");
034:   openMenuItem.addActionListener(this);
035:   popupMenu.add(openMenuItem);
036:   saveMenuItem = new JMenuItem("Save");
037:   saveMenuItem.addActionListener(this);
038:   popupMenu.add(saveMenuItem);
039:   closeMenuItem = new JMenuItem("Close");
040:   closeMenuItem.addActionListener(this);
041:   popupMenu.add(closeMenuItem);
042:   popupMenu.addSeparator();
043:   exitMenuItem = new JMenuItem("Exit");
044:   exitMenuItem.addActionListener(this);
045:   popupMenu.add(exitMenuItem);
046: 
047:   // Register frame listener so menu pops on the
048:   // proper mouse click depending on the look and feel
049:   addMouseListener(new PopupHandler());
050:  }
051: 
052:  // Constructor
053:  public PopupDemo() {
054: 
055:   // Select local system look and feel
056:   try {
057:    UIManager.setLookAndFeel(
058:     UIManager.getSystemLookAndFeelClassName());
059:   } catch (Exception e) { }
060: 
061:   // End program when window closes
062:   addWindowListener(new WindowAdapter() {
063:    public void windowClosing(WindowEvent e) {
064:     System.exit(0);
065:    }
066:   });
067: 
068:   createPopupMenu();
069:   Container content = getContentPane();
070:   content.add(new JLabel("Click inside the window"));
071:  }
072: 
073:  // All popup menu items are registered on this event handler
074:  public void actionPerformed(ActionEvent e) {
075:   JMenuItem menuItem = (JMenuItem)e.getSource();
076:   
077:   // Show selected command text (just for demonstration)
078:   JOptionPane.showMessageDialog(this, 
079:    "Command: " + menuItem.getText());
080: 
081:   // Find out which command was selected
082:   if (menuItem.equals(openMenuItem)) {
083:    // ... do open command
084:   }
085:   if (menuItem.equals(saveMenuItem)) {
086:    // ... do save command
087:   }
088:   if (menuItem.equals(closeMenuItem)) {
089:    // ... do close command
090:   }
091:   if (menuItem.equals(exitMenuItem)) {
092:    System.exit(0);  // Only implemented command
093:   }
094:  }
095: 
096:  public static void main(String[] args) {
097:   PopupDemo app = new PopupDemo();
098:   app.setTitle("Popup Menu Demonstration");
099:   app.setSize(320, 240);
100:   app.show();
101:  }
102: }
Return to top

Listing 22-14 ToolDemo/ToolDemo.java Page 504

Return to top
001: import javax.swing.*;
002: import java.awt.*;
003: import java.awt.event.*;
004: 
005: public class ToolDemo extends JFrame {
006: 
007:  // The popup menu object
008:  protected JPopupMenu popupMenu;
009: 
010:  // the toolbar object
011:  protected JToolBar toolbar;
012: 
013:  // Each Action object responds to a toolbar or menu selection
014:  Action openAction;
015:  Action saveAction;
016:  Action closeAction;
017:  Action exitAction;
018: 
019:  // Inner class pops up the menu when the proper mouse
020:  // click or release is detected for the current look-and-feel
021:  class PopupHandler extends MouseAdapter {
022:   public void mousePressed(MouseEvent e) {
023:    if (e.isPopupTrigger())
024:     popupMenu.show(e.getComponent(), e.getX(), e.getY());
025:   }
026:   public void mouseReleased(MouseEvent e) {
027:    if (e.isPopupTrigger())
028:     popupMenu.show(e.getComponent(), e.getX(), e.getY());
029:   }
030:  } 
031: 
032:  // Create the Action objects, one for each command in 
033:  // the toolbar and popup menu
034:  protected void createActionObjects() {
035:   ImageIcon icon;  // For loading the toolbar and menu icons
036: 
037:   // Create the Open command Action handler
038:   icon = new ImageIcon("openicon.gif");
039:   openAction = new AbstractAction("Open", icon) {
040:    public void actionPerformed(ActionEvent e) {
041:     // ... do Open command
042:    }
043:   };
044: 
045:   // Create the Save command Action handler
046:   icon = new ImageIcon("saveicon.gif");
047:   saveAction = new AbstractAction("Save", icon) {
048:    public void actionPerformed(ActionEvent e) {
049:     // ... do Save command
050:    }
051:   };
052: 
053:   // Create the Close command Action handler
054:   icon = new ImageIcon("closeicon.gif");
055:   closeAction = new AbstractAction("Close", icon) {
056:    public void actionPerformed(ActionEvent e) {
057:     // ... do Close command
058:    }
059:   };
060: 
061:   // Create the Exit command Action handler
062:   icon = new ImageIcon("exiticon.gif");
063:   exitAction = new AbstractAction("Exit", icon) {
064:    public void actionPerformed(ActionEvent e) {
065:     System.exit(0);
066:    }
067:   };
068:  }
069: 
070:  // Create the popup menu and its commands
071:  // Assumes all Action objects are initialized
072:  protected void createPopupMenu() {
073:   popupMenu = new JPopupMenu();
074:   popupMenu.add(openAction);
075:   popupMenu.add(saveAction);
076:   popupMenu.add(closeAction);
077:   popupMenu.addSeparator();
078:   popupMenu.add(exitAction);
079:  }
080: 
081:  // Create the toolbar
082:  // Assumes all Action objects are initialized
083:  protected void createToolbar() {
084:   toolbar = new JToolBar();
085:   toolbar.add(openAction);
086:   toolbar.add(saveAction);
087:   toolbar.add(closeAction);
088:   toolbar.addSeparator();
089:   toolbar.add(exitAction);
090:  }
091: 
092:  // Constructor
093:  public ToolDemo() {
094: 
095:   // Select local system look and feel
096:   // One of the following two choices produces the best
097:   // looking toolbars
098:   try {
099:    UIManager.setLookAndFeel(
100:    "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
101: //   "javax.swing.plaf.metal.MetalLookAndFeel");
102:   } catch (Exception e) { }
103: 
104:   // End program when window closes
105:   addWindowListener(new WindowAdapter() {
106:    public void windowClosing(WindowEvent e) {
107:     System.exit(0);
108:    }
109:   });
110: 
111:   createActionObjects();
112:   createPopupMenu();
113:   createToolbar();
114: 
115:   // Register frame listener so menu pops on the
116:   // proper mouse click depending on the look and feel
117:   addMouseListener(new PopupHandler());
118: 
119:   Container content = getContentPane();
120:   // BorderLayout is required for a floating toolbar
121:   content.setLayout(new BorderLayout());
122:   content.add(toolbar, BorderLayout.NORTH);
123:   toolbar.setFloatable(true);
124:   content.add(new JLabel("Click inside the window"));
125:  }
126: 
127:  public static void main(String[] args) {
128:   ToolDemo app = new ToolDemo();
129:   app.setTitle("Tool bar and Action demo");
130:   app.setSize(320, 240);
131:   app.show();
132:  }
133: }
Return to top