First Swing Component

In your source code, you include the Swing package by adding an import statement:

import javax.swing.*;
Now you’re ready to replace your Button objects with JButton objects. We’ll also set up the application to take advantage of Swing’s L&F capabilities; we’ve put another row of buttons at the bottom of the frame that let you select one of the standard L&Fs:

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

public class ToolbarFrame2 extends Frame {

  // This time, let's use JButtons!
  JButton cutButton, copyButton;

  public ToolbarFrame2( ) {
    super("Toolbar Example (Swing)");
    setSize(250, 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( ));
      }
    };
  
    // JPanel works similarly to Panel, so we'll use it.
    JPanel toolbar = new JPanel( );
    toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));

    cutButton = new JButton("Cut");
    cutButton.addActionListener(printListener);
    toolbar.add(cutButton);

    copyButton = new JButton("Copy");
    copyButton.addActionListener(printListener);
    toolbar.add(copyButton);

    add(toolbar, BorderLayout.NORTH);
  }

  public static void main(String args[]) {
    ToolbarFrame2 tf2 = new ToolbarFrame2( );
    tf2.setVisible(true);
  }
}

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:


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

public class ToolbarFrame1 extends Frame {

	Button cutButton, copyButton, pasteButton;

	public ToolbarFrame1() {
		super("Toolbar Example (AWT)");
		setSize(250, 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);
	}
}

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, you get this capability “for free” with JFrame’s defaultCloseOperation property.

Upgrading Your AWT Programs

One of the benefits of object-oriented languages is that you can upgrade pieces of a program without rewriting the rest. While practice is never as simple as theory, with Swing it’s close. You can use most of the Swing components as drop-in replacements for AWT components with ease. The components sport many fancy new features worth exploiting, but they still maintain the functionality of the AWT components you’re familiar with. As a general rule, you can stick a “J” in front of your favorite AWT component and put the new class to work as a Swing component. Constructors for components such as JButton, JTextField, and JList can be used with the same arguments and generate the same events as Button, TextField, and List. Some Swing containers, like JFrame, take a bit of extra work, but not much.
 
Graphical buttons are essential to modern user interfaces. Nice monitors and cheap hardware have made icons almost a necessity. The AWT package in Java does not directly support image buttons. You could write an extension to support them easily enough, but why bother when Swing’s JButton class provides a standard way to add image buttons?