New to Java? We'll help you get started with our revised beginner's tutorial, or our free online textbook.


Get the latest Java books
h t t p : / /w w w . j a v a c o f f e e b r e a k . c o m /

Java Coffee Break

Menu



Learning Java

Articles
Author Profiles
Lessons
FAQ's
Books
Newsletter
Tutorials
Talk Java!

Using Java

Applets
JavaBeans
Servlets
Resources
Discuss Java


Looking for Java resources? Check out the Java Coffee Break directory!

Developing your first Swing application

Using the Swing API in your own applications is quite straightforward, as is converting existing applications to Swing. The first thing that all Swing applications must do is import the Swing packages. Beta versions of JDK1.2 used a different package location, but the official release stores most of the Swing related packages under the javax.* extensions hierarchy.

// Import AWT classes
import java.awt.*;
// Import AWT event classes
import java.awt.event.*;
// Import Swing classes
import javax.swing.*;

Note that there are many more Swing packages, covering very specific areas of functionality. As your application uses more and more of the functionality Swing offers, you'll need to add more packages. For the moment, however, only javax.swing is required.

Advice when using Swing

Here are a few rules of thumb, that will assist you when using Swing :-

  • Every AWT component (eg java.awt.Button), has a corresponding Swing component. Just at J to the beginning (Button -> JButton).
  • Adding components to a JFrame is slightly different to a Frame. You must add your components to JFrame.getContentPane().

Using these rules, it's quite straightforward to convert an existing application to Swing, or to design one from scratch. So let's take a look at a simple application, that displays a small frame (centered in the middle of the screen). The frame will display a label, as well as a button that closes the window. We'll take a look at the AWT version first, and compare it to the Swing version.

Writing the AWT version

Back to main


Copyright 1998, 1999, 2000 David Reilly

Privacy | Legal | Linking | Advertise!

Last updated: Monday, June 05, 2006