The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Getting Started with Swing

A Quick Tour of a Swing Application's Code

This section takes you through the code for the SwingApplication program. The next lesson, Swing Features and Concepts(in the Creating a GUI with JFC/Swing trail), provides full explanations of the topics introduced in this section. It also provides a bigger, more realistic example that you can use to expand and test your Swing knowledge.

SwingApplication brings up a window that looks like this:

SwingApplication

Each time the user clicks the button, the label is updated. You can find the whole program in SwingApplication.java(in a .java source file).

The code in SwingApplication.java accomplishes the following tasks:

Importing Swing Packages

The following line imports the main Swing package:
import javax.swing.*;


Note:  Early JFC 1.1 and Java 2 SDK v 1.2 beta releases used different names for the Swing packages. See Swing Package Names for details.

Most Swing programs also need to import the two main AWT packages:

import java.awt.*;
import java.awt.event.*;

Choosing the Look and Feel

Swing allows you to specify which look and feel your program uses -- Java look and feel, Windows look and feel, CDE/Motif look and feel, and so on. The bold code in the following snippet shows you how SwingApplication specifies the look and feel:
public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel(
            UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) { }

    ...//Create and show the GUI...
}
The preceding code essentially says, "I don't care whether the user has chosen a look and feel -- use the cross-platform look and feel (the Java look and feel)." You already know what the Java look and feel looks like, since almost all of our screenshots show it.

For more information on specifying the look and feel, see How to Set the Look and Feel(in the Creating a GUI with JFC/Swing trail).

Setting Up the Top-Level Container

Every program that presents a Swing GUI contains at least one top-level Swing container. For most programs, the top-level Swing containers are instances of JFrame, JDialog, or (for applets) JApplet. Each JFrame object implements a single main window, and each JDialog implements a secondary window. Each JApplet object implements an applet's display area within a browser window. A top-level Swing container provides the support that Swing components need to perform their painting and event handling.

The SwingApplication example has only one top-level container, a JFrame. When the user closes the frame, the application exits. Here is the code that sets up and shows the frame:

public class SwingApplication {
    ...
    public static void main(String[] args) {
	...
        JFrame frame = new JFrame("SwingApplication");
        //...create the components to go into the frame...
        //...stick them in a container named contents...
        frame.getContentPane().add(contents, BorderLayout.CENTER);

        //Finish setting up the frame, and show it.
        frame.addWindowListener(...);
        frame.pack();
        frame.setVisible(true);
    }
}

For more information about top-level containers, see Swing Components and the Containment Hierarchy(in the Creating a GUI with JFC/Swing trail).

Setting Up Buttons and Labels

Like most GUIs, the SwingApplication GUI contains a button and a label. (Unlike most GUIs, that's about all that SwingApplication contains.) Here's the code that initializes the button:
JButton button = new JButton("I'm a Swing button!");
button.setMnemonic(KeyEvent.VK_I);
button.addActionListener(...create an action listener...);
The first line creates the button. The second sets the I key as the mnemonic that the user can use to simulate a click of the button. For example, in the Java look and feel, typing Alt-i results in a button click. The third line registers an event handler for the button click. You'll see the event-handling code for this program in Handling Events.

Here's the code that initializes and manipulates the label:

...//where instance variables are declared:
private static String labelPrefix = "Number of button clicks: ";
private int numClicks = 0;

...//in GUI initialization code:
final JLabel label = new JLabel(labelPrefix + "0    ");
...
label.setLabelFor(button);

...//in the event handler for button clicks:
label.setText(labelPrefix + numClicks);
The preceding code is pretty straightforward, except for the line that invokes the setLabelFor method. That code exists solely to hint to assistive technologies that the label describes the button. For more information, see Supporting Assistive Technologies.

For more information about Swing components such as buttons and labels, see Using Swing Components(in the Creating a GUI with JFC/Swing trail).

Adding Components to Containers

SwingApplication groups the label and button in a container (a JPanel) before adding the components to the frame. Here's the code that initializes the panel:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
pane.setLayout(new GridLayout(0, 1));
pane.add(button);
pane.add(label);
The first line of code creates the panel. The second line adds a border to it. We'll discuss the border later.

The third line of code creates a layout manager that forces the panel's contents to be displayed in a single column. The last lines add the button and label to the panel. Adding the button and label to the panel means they are controlled by the panel's layout manager. Specifically, a container's layout manager determines the size and position of each component that's been added to the container.

Layout management concepts are discussed in Layout Management(in the Creating a GUI with JFC/Swing trail). To learn how to use individual layout managers, see Laying Out Components Within a Container(in the Creating a GUI with JFC/Swing trail).

Adding Borders Around Components

Here, again, is the code that adds a border to the panel:
pane.setBorder(BorderFactory.createEmptyBorder(
                                30, //top
                                30, //left
                                10, //bottom
                                30) //right
                                );
This border simply provides some empty space around the panel's contents -- 30 extra pixels on the top, left, and right, and 10 extra pixels on the bottom. Borders are a feature that JPanel inherits from the JComponent class.

Border concepts are discussed in Layout Management(in the Creating a GUI with JFC/Swing trail) and Painting(in the Creating a GUI with JFC/Swing trail). See How to Use Borders(in the Creating a GUI with JFC/Swing trail) for information about using the border API.

Handling Events

The SwingApplication example contains two event handlers. One handles button clicks (action events); the other handles window closing (window events). Here is the event-handling code from SwingApplication:
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        numClicks++;
        label.setText(labelPrefix + numClicks);
    }
});
...
frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
	System.exit(0);
    }
});
You can read about Swing event handling in Event Handling(in the Creating a GUI with JFC/Swing trail) and Writing Event Listeners(in the Creating a GUI with JFC/Swing trail).

Dealing with Thread Issues

The SwingApplication program is thread safe. Once its GUI is visible, its only GUI manipulation (updating the label) occurs in an event handler. Because the event handler runs in the same thread that performs all event handling and painting for the application, there's no possibility that two threads will try to manipulate the GUI at once.

However, it can be all too easy to introduce thread problems into a program. See Threads and Swing(in the Creating a GUI with JFC/Swing trail) for information about thread safety in Swing.

Supporting Assistive Technologies

Support for assistive technologies -- devices such as screen readers that provide alternate ways of accessing information in a GUI -- is already included in every Swing component. The only code in SwingApplication that exists solely to support assistive technologies is this:
label.setLabelFor(button);
Assistive technologies can get plenty of information from Swing components, without any special code from you. For example, assistive technologies can automatically get the text information set by the following lines of code:
JButton button = new JButton("I'm a Swing button!");
label = new JLabel(labelPrefix + "0    ");
label.setText(labelPrefix + numClicks);
JFrame frame = new JFrame("SwingApplication");
See How to Support Assistive Technologies(in the Creating a GUI with JFC/Swing trail) for more information about how you can ensure that your programs work well with tools that use the Accessibility API to query components.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.