< Zurück | Inhalt | Weiter >

Part III


Graphical User Interfaces

Chapter 16

Getting in the Swing of Things: Designing a GUI for BudgetPro


Sometimes you gotta have a GUI; even we will admit that command lines only go so far. When it comes to simple interactions with casual users, a Graphical User Interface is a great step forward . . . if it’s done well. The toolkit for building such an interface with Java is called Swing. The original Java toolkit is AWT (A Windowing Toolkit), and is still in use, but much less attractive. We’ll take a quick look at some major pieces of Swing, and show a complete example—a GUI for our budget application. After this example, you will have the tools you need to construct some real GUIs on your own.



• The Swing GUI paradigm.

• A simple standalone Swing application.

• Some basic Swing objects—buttons and labels.

• A bit about layout managers.

• A more complex object—the JTable.



Let’s take a look at a very simple (in its function, not in its composition) Swing program—a simple “Hello, world” that will appear in a window (Example 16.1).


Example 16.1 A simple Swing application

import java.awt.*; import javax.swing.*;

public class hw


public static void main(String[] args)


//Create the top-level container JFrame frame = new JFrame();

JLabel hi = new JLabel("Hello, world."); frame.getContentPane().add(hi, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); // kicks the UI into action frame.setVisible(true);

} // main

} // class hw


Now compile this program and run it from the command line like this:

$ javac hw.java

$ java hw

You should then see a small window appear, looking as in Figure 16.1.


Figure 16.1 “Hello, world” in a Swing window


16.3 Stompin’ at the Savoy, or The Swing Paradigm 343

While this may look like a lot of extra junk just to say “Hello, world,” re- member that a GUI is not just providing output in fancy windows, but also monitoring and responding to a wide variety of user inputs—a capability of which we make little or no use in this example. But you can see some of this extra capability—grab the lower left corner of the window frame and expand and resize the window.


When we say “Swing,” we generally mean the set of classes in the javax.swing package and its subpackages (such as javax.swing.table). The packages are libraries of code that give you predefined classes from which you can construct a GUI for your application. The programs you write will be written in Java, the syntax will look like Java, but there will be a lot of creation of classes, uses of interfaces, implementations of abstract classes, and a variety of method calls that all deal with these Swing classes.

So what’s going on with all this stuff? What can we expect to do, see, write? In most applications that a programmer writes, it is the job of the pro- grammer to design and write the code for the main execution path of the pro- gram. “Yes, every program has a beginning, middle, and an end” (with apologies to “Seymour and his frozen yoghurt stand,” from Sesame Street). But it’s not quite the same with Swing. While it does have to have a beginning, middle, and end (these are, after all, basic Von Neumann architecture machines), the big difference is that you do not have to write most of the control logic; it comes as part of the Swing set.

Look at it this way. With Swing, as with other GUI toolkits, you don’t have to write code to deal with the mouse, keyboard shortcuts, or painting characters onto a graphical screen. You don’t have to write all the code associated with a button press, because, while it seems simple enough, a button press is really a quite complex user interaction, involving repainting of the button’s border, possibly its shading or changing its icon, coordinating that with the mouse presses and releases, and deciding whether the releases happen within or without the boundaries of the button—all this and more, just for a simple button press. All this has been done for you, and packaged up into Swing classes.

So what is left for you to do? You have to:

• Construct the various items that will appear on the screen (in one or more windows).

• Specify the location of these objects in the windows (layout).

• Provide snippets of code that are the actions associated with various events (events happen, for example, when a button is pressed or a mouse is clicked). These actions are the guts of the code that make your application behave how you want.

Remember, some behaviors are enforced by the GUI as part of standard “look and feel.” Some things, like layout, are up to you to do well so long as you keep within the standard UI guidelines. And some is just specific to your application.

With that in mind, let’s walk through the “Hello, world” example for a brief description of what each line does.

We begin with some import statements, to resolve references to both Swing and AWT classes. Swing is built on top of AWT, so some of the classes that you use will actually be AWT classes. The biggest difference this makes to you is in the import statements.

We then begin our class declaration, followed by the definition of the only method in this class, main(). Swing applications will typically have other methods, but for our simple example we only need this one.

Now comes some real Swing. The creation of a JFrame object is very im- portant. In Swing we need to have containers to hold the objects that we want to display. The JFrame is a top-level container, one specifically meant to hold other objects, but also meant to be the first one of a containment hierarchy. (There are only three such top-level containers in Swing: JFrame, JDialog, and JApplet.)

Next we create a JLabel. It’s a Swing object meant to hold small amounts of text. The text can be either constant or changing, but it’s not user-editable (that would be a different kind of Swing object).

We add the label to the frame, so that when the window (the JFrame) appears, it will show our text inside.

The setDefaultCloseAction() does what you think. When you press the X in the upper right of the window frame (or wherever your window man- ager puts it), then not only will the window go away, but the program will stop running. (This is not the standard default value since JFrames can contain

16.4 Slow, Slow, Quick-Quick, Slow: The Basic Swing Objects 345


other JFrames, and for most frames you wouldn’t want closing the frame to quit the program.)

When we “pack” the frame, that’s when the real magic happens. It kicks off the GUI activity on a separate thread, but also packs the various pieces that we’ve added to the frame, sizing them as best it can to fit into the frame, and sizing the frame to hold all the pieces. We see little of that with our example, which has only one label.

As an aside, pack() is inherited from awt.Window, which describes the “magic” thus:

A component is displayable when it is connected to a native screen resource. A component is made displayable either when it is added to a displayable containment hierarchy or when its containment hierarchy is made dis- playable. A containment hierarchy is made displayable when its ancestor window is either packed or made visible.

So pack()-ing the frame connects it to a “native screen resource,” which effectively gets the whole GUI thing going.

And now back to the business at hand.

Finally, the setVisible() call makes the window appear. Then the main() is done. In case you’re wondering, go ahead and put a System.out.println() message after the setVisible(). It will be printed right away. The main() has ended; the GUI activity is happening on another thread.


Let’s take a quick look at a variety of Swing objects that you can use to build a GUI. Like any job of craftsmanship, it helps to be familiar with your tools. What you can build will be aided (and limited) by the tools with which you build, and by how familiar you are with them. Here are some pieces which can be put together to make Swing GUIs:



radio button

check box

combo box



text field

text area

text pane





tool tip

progress bar

color chooser

file chooser


split pane

scroll pane

tabbed pane


16.7.1 Overview

16.7.2 Creating Pieces