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 ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.