Book Home Java Enterprise in a Nutshell Search this book

Chapter 2. Swing and AWT Architecture

Contents:

A Simple Graphical User Interface
Components
Properties
Containers and Containment
Layout Management
Event Handling
Swing Component Architecture

The Abstract Windowing Toolkit (AWT) provides basic facilities for creating graphical user interfaces (GUIs), and also for drawing graphics, as we'll discuss in a later chapter. AWT has been a core part of Java since Java 1.0. The GUI features of AWT are layered on top of the native GUI system of the underlying platform. In other words, when you create a graphical push button with AWT, AWT creates a Windows push button, or a Macintosh push button, or a Motif push button, or whatever, depending on the platform on which the application is running. In Java 1.1, AWT was extended to allow the creation of "lightweight" GUI components that do not have corresponding native GUI components behind them.

Swing is a new GUI toolkit that is available as a core part of the Java 2 platform and also as an extension to Java 1.1. Swing is an extension of the AWT toolkit, not an entirely new toolkit. All of the GUI components provided by Swing are lightweight components, so they do not rely on the underlying native GUIs. The result is that Swing is more portable, making it much easier to write graphical applications that behave the same on all platforms. Swing is also larger and more comprehensive than AWT. In addition to a complete and powerful set of GUI components, Swing provides a number of utilities that make it easier to write graphical applications.

Swing offers a great step forward when compared to AWT. You should use Swing in all your Java 2 applications. You should also seriously consider using it as an extension for Java 1.1 applications. Unfortunately, at the time of this writing, common web browsers do not yet support Swing, so if you are writing applets, you should either run those applets under the Java Plug-in, or you should avoid the use of Swing and rely exclusively on the features of AWT. See Chapter 7, "Applets", for more information on applets.

This chapter introduces the basic architecture used by both AWT and Swing. For more information on Swing and AWT, see Java Swing, by Robert Eckstein, Marc Loy, and Dave Wood (O'Reilly), and Java AWT Reference, by John Zukowski (O'Reilly), respectively.

2.1. A Simple Graphical User Interface

Example 2-1 is a simple program that uses Swing to create and display a graphical user interface. Figure 2-1 shows the GUI created by this program.

figure

Figure 2-1. The GUI of the DisplayMessage program

The DisplayMessage program is designed for use in a shell script or batch file.[1] If you invoke the program on the command line with the text of a question, it displays the question to the user and waits for the user to click the Yes button or the No button. The program sets its exit code based on the user's response, so a shell script can examine this exit code to determine how the user responded. The program expects from one to three command-line arguments that specify the text of the question and the text for the "Yes" and "No" buttons, respectively. For example, you might invoke the program like this:

[1]Because the Java Virtual Machine takes a long time to start up, it is not actually practical to use this program in a shell script. It is a useful example nevertheless.

% java DisplayMessage "Do you really want to quit?" "Yes, Please", "No, Thanks"

The example illustrates step-by-step how to create a Swing GUI. Don't worry if you don't understand the details of this program yet. If you read it through once now to get the big picture, you can refer back to it as you read the sections that follow.

Example 2-1. Creating a Simple GUI with Swing

import java.awt.*;             // AWT classes
import javax.swing.*;          // Swing components and classes
import javax.swing.border.*;   // Borders for Swing components
import java.awt.event.*;       // Basic event handling 

public class DisplayMessage {
  public static void main(String[] args) {
    /*
     * Step 1: Create the components
     */
    JLabel msgLabel = new JLabel();      // Component to display the question
    JButton yesButton = new JButton();   // Button for an affirmative response
    JButton noButton = new JButton();    // Button for a negative response

    /*
     * Step 2: Set properties of the components
     */
    msgLabel.setText(args[0]);                           // The msg to display
    msgLabel.setBorder(new EmptyBorder(10,10,10,10));    // A 10-pixel margin 
    yesButton.setText((args.length >= 2)?args[1]:"Yes"); // Text for yes button
    noButton.setText((args.length >= 3)?args[2]:"No");   // Text for no button

    /*
     * Step 3: Create containers to hold the components
     */
    JFrame win = new JFrame("Message");  // The main application window
    JPanel buttonbox = new JPanel();     // A container for the two buttons
    
    /*
     * Step 4: Specify LayoutManagers to arrange components in the containers
     */
    win.getContentPane().setLayout(new BorderLayout()); // Layout on borders
    buttonbox.setLayout(new FlowLayout());              // Layout left-to-right

    /*
     * Step 5: Add components to containers, with optional layout constraints
     */
    buttonbox.add(yesButton);            // Add yes button to the panel
    buttonbox.add(noButton);             // Add no button to the panel
    
    // add JLabel to window, telling the BorderLayout to put it in the middle
    win.getContentPane().add(msgLabel, "Center");        

    // add panel to window, telling the BorderLayout to put it at the bottom
    win.getContentPane().add(buttonbox, "South");  
    
    /*
     * Step 6: Arrange to handle events in the user interface
     */
    yesButton.addActionListener(new ActionListener() {  // Note: inner class
      // This method is called when the Yes button is clicked
      public void actionPerformed(ActionEvent e) { System.exit(0); }
    });

    noButton.addActionListener(new ActionListener() {   // Note: inner class
      // This method is called when the No button is clicked
      public void actionPerformed(ActionEvent e) { System.exit(1); }
    });

    /*
     * Step 7: Display the GUI to the user
     */
    win.pack();   // Set the size of the window based on its children's sizes
    win.show();   // Make the window visible
  }
}


Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.

This HTML Help has been published using the chm2web software.