Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
This section takes you through the code for theSwingApplication
program. The next lesson, Swing Features and Concepts, 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:Each time the user clicks the button, the label is updated. You can find the whole program in
SwingApplication.java
.The code in
SwingApplication.java
accomplishes the following tasks:
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.*;
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 howSwingApplication
specifies the look and feel: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.public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } ...//Create and show the GUI... }For more information on specifying the look and feel, see How to Set the Look and Feel.
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 ofJFrame
,JDialog
, or (for applets)JApplet
. EachJFrame
object implements a single main window, and eachJDialog
implements a secondary window. EachJApplet
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, aJFrame
. 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.
Like most GUIs, theSwingApplication
GUI contains a button and a label. (Unlike most GUIs, that's about all thatSwingApplication
contains.) Here's the code that initializes the button: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.JButton button = new JButton("I'm a Swing button!"); button.setMnemonic(KeyEvent.VK_I); button.addActionListener(...create an action listener...);Here's the code that initializes and manipulates the label:
The preceding code is pretty straightforward, except for the line that invokes the...//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);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.
SwingApplication
groups the label and button in a container (aJPanel
) before adding the components to the frame. Here's the code that initializes the panel:The first line of code creates the panel. The second line adds a border to it. We'll discuss the border later.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 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. To learn how to use individual layout managers, see Laying Out Components Within a Container.
Here, again, is the code that adds a border to the panel: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 thatpane.setBorder(BorderFactory.createEmptyBorder( 30, //top 30, //left 10, //bottom 30) //right );JPanel
inherits from theJComponent
class.Border concepts are discussed in Layout Management and Painting. See How to Use Borders for information about using the border API.
TheSwingApplication
example contains two event handlers. One handles button clicks (action events); the other handles window closing (window events). Here is the event-handling code fromSwingApplication
:You can read about Swing event handling in Event Handling and Writing Event Listeners.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); } });
TheSwingApplication
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 for information about thread safety in Swing.
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 inSwingApplication
that exists solely to support assistive technologies is this: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:label.setLabelFor(button);See How to Support Assistive Technologies for more information about how you can ensure that your programs work well with tools that use the Accessibility API to query components.JButton button = new JButton("I'm a Swing button!"); label = new JLabel(labelPrefix + "0 "); label.setText(labelPrefix + numClicks); JFrame frame = new JFrame("SwingApplication");
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.