2.2 A Simple AWT Application


You probably have some programs lying around that use regular AWT buttons that you'd love to replace with image buttons, but you don't have the time or, honestly, the necessity to produce your own image button class. Let's look at a simple application that demonstrates an upgrade path you can use on your own programs.

First, let's look at the code for this very simple application:

// ToolbarFrame1.java // A simple frame containing a "toolbar" made up of several java.awt.Button // objects. We'll be converting the Buttons to JButtons in the ToolbarFrame2.java // file. // import java.awt.*; import java.awt.event.*; public class ToolbarFrame1 extends Frame {   Button cutButton, copyButton, pasteButton;   public ToolbarFrame1( ) {     super("Toolbar Example (AWT)");     setSize(450, 250);     addWindowListener(new WindowAdapter( ) {       public void windowClosing(WindowEvent e) {         System.exit(0);       }     });     ActionListener printListener = new ActionListener( ) {       public void actionPerformed(ActionEvent ae) {         System.out.println(ae.getActionCommand( ));       }     };     Panel toolbar = new Panel( );     toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));     cutButton = new Button("Cut");     cutButton.addActionListener(printListener);     toolbar.add(cutButton);     copyButton = new Button("Copy");     copyButton.addActionListener(printListener);     toolbar.add(copyButton);     pasteButton = new Button("Paste");     pasteButton.addActionListener(printListener);     toolbar.add(pasteButton);     // The "preferred" BorderLayout add call     add(toolbar, BorderLayout.NORTH);    }   public static void main(String args[]) {     ToolbarFrame1 tf1 = new ToolbarFrame1( );     tf1.setVisible(true);   } }

Our application has the very simple interface that is in Figure 2-1.

Figure 2-1. A simple application using three java.awt.Button objects
figs/swng2.0201.gif

These buttons don't really do anything except report that they've been pressed. A standard 1.1-style handler for action events reports button presses to standard output. It's not exciting, but it lets us demonstrate that Swing buttons work the same way as AWT buttons. If you examine the code you'll notice that we had to register a window listener to tell when the user is trying to close the window, and explicitly exit the program in response. Once you update your programs to use Swing's JFrame rather than AWT's Frame (as we will for the final example in this chapter), you get this capability "for free" with JFrame's defaultCloseOperation property, described in Table 8-8.



Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net