O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Including Your First Swing Component

The first step in adding a Swing component to your application is preparing the Swing package for use. As long as you have installed SDK 1.2 or later, you don’t have to take any special steps to use the Swing classes. If you’re preparing an application to run with JDK 1.1, you’ll need to put the swingall.jar file on the CLASSPATH so that the Swing components are available during compilation and at runtime.

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:

// ToolbarFrame2.java // The Swing-ified button example // import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ToolbarFrame2 extends Frame { // This time, let's use JButtons! JButton cutButton, copyButton, pasteButton; JButton javaButton, macButton, motifButton, winButton; public ToolbarFrame2( ) { super("Toolbar Example (Swing)"); setSize(450, 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required