Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Java Lecture 15: Swing I. Part I. Teach/learn online

JavaFAQ Home » Java Lectures by Anatoliy Malyarenko Go to all tips in Java Lectures by Anatoliy Malyarenko

Bookmark and Share

Swing I


  • Contents of the lecture.
  • Overview of the Swing API.
  • Your first Swing program.
  • Example two: SwingApplication.
  • Example three: CelsiusConverter.

Overview of the Swing API

The Swing package is part of the JavaTM+ Foundation Classes (JFC) in the Java platform. The JFC encompasses a group of features to help people build GUIs; Swing provides all the components from buttons to split panes and tables.

The Swing package was first available as an add-on to JDK 1.1. Prior to the introduction of the Swing package, the Abstract Window Toolkit (AWT) components provided all the UI components in the JDK 1.0 and 1.1 platforms. Although the Java 2 Platform still supports the AWT components, we strongly encourage you to use Swing components instead. You can identify Swing components because their names start with J. The AWT button class, for example, is named Button, whereas the Swing button class is named JButton. In addition, the AWT components are in the java.awt package, whereas the Swing components are in the javax.swing package.

As a rule, programs should not use "heavyweight" AWT components alongside Swing components. Heavyweight components include all the ready-to-use AWT components, such as Menu and ScrollPane, and all components that inherit from the AWT Canvas and Panel classes.

When Swing components (and all other "lightweight" components) overlap with heavyweight components, the heavyweight component is always painted on top.

Your first Swing program

Here, we examine the code for a simple program, HelloWorldSwing. Later, the examples will become progressively more difficult as we introduce and explain more features.

Here's a snapshot of the HelloWorldSwing program:

And here's the code for HelloWorldSwing:


import javax.swing.*;

public class HelloWorldSwing {
   public static void main(String[] args) {
      JFrame frame = new JFrame("HelloWorldSwing");
      final JLabel label = new JLabel("Hello World");

This is one of the simplest Swing applications you can write. It doesn't do much, but the code demonstrates the basic code in every Swing program:

  • Import the pertinent packages.
  • Set up a top-level container.

The first line imports the main Swing package:


import javax.swing.*;

This is the only package that HelloWorldSwing needs. However, most Swing programs also need to import two AWT packages:


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

These packages are required because Swing components use the AWT infrastructure, including the AWT event model. The event model governs how a component reacts to events, such as button clicks and mouse motion.

Every program with a Swing GUI must contain at least one top-level Swing container. A top-level Swing container provides the support that Swing components need to perform their painting and event handling. There are three top-level Swing containers: JFrame, JDialog, and (for applets) JApplet. Each JFrame object implements a single main window, and each JDialog implements a secondary window (a window that's dependent on another window).

Each JApplet object implements an applet's display area within a browser window.

The HelloWorldSwing example has only one top-level container, a JFrame. A frame, implemented as an instance of the JFrame class, is a window that has decorations, such as a border, a title, and buttons for iconifying and closing the window. Applications with a GUI typically use at least one frame.

Here is the code that sets up and shows the frame:


JFrame frame = new JFrame("HelloWorldSwing");
HelloWorldSwing also has one component, a label that reads "Hello World." These two
lines of code construct and then add the component to the frame:

final JLabel label = new JLabel("Hello World");
To close the window when the close button is clicked, we include this code in our HelloWorldSwing program:



JFrame provides the setDefaultCloseOperation method to configure the default action for when the user clicks the close button. For single-window applications, most likely you want the application to exit. The EXIT_ON_CLOSE constant lets you specify this, as of version 1.3 of the Java 2 Platform.

Example two: SwingApplication

Let's look at another simple program, SwingApplication. Each time the user clicks the button (JButton), the label (JLabel) is updated.

Look and feel

The following figures show three views of a GUI that uses Swing components. Each picture shows the same program, SimpleExample, but with a different look and feel.

Figure 1: Java look and feel

Figure 2: CDE/Motif look and feel

Figure 3: Windows look and feel

Swing allows you to specify which look and feel your program uses -- Java look and feel, CDE/Motif look and feel, Windows look and feel, and so on. The code in boldface type in the following snippet shows you how SwingApplication specifies its look and feel:


public static void main(String[] args) {
   try { UIManager.setLookAndFeel(
   } catch (Exception e) { }
      ...// Create and show the GUI...

The preceding code essentially says, "I don't care whether the user has chosen a look and feel-use the cross-platform look and feel (the Java look and feel)."

Setting up buttons and labels

Like most GUIs, the SwingApplication GUI contains a button and a label. (Unlike most GUIs, that's about all that SwingApplication contains.) Here's the code that initialises the button:


JButton button = new JButton("I'm a Swing button!");

button.addActionListener(...create an action listener...);

The first line creates the button. The second sets the letter "i" as the mnemonic that the user can use to simulate a click of the button. For example, in the Java look and feel, typing Alt-i results in a button click. The third line registers an event handler for the button click, as
discussed later.

Here's the code that initialises and manipulates the label:


...// where instance variables are declared:

private static String labelPrefix ="Number of button clicks: ";

private int numClicks = 0;

...// in GUI initialisation code:
final JLabel label = new JLabel(labelPrefix + "0 ");


...// in the event handler for button clicks:
label.setText(labelPrefix + numClicks);

The preceding code is pretty straightforward, except for the line that invokes the setLabelFor method. That code exists solely to hint to assistive technologies that the label describes the button.

Now that you know how to set up buttons, you also know how to set up check boxes and radio buttons, as they all inherit from the AbstractButton class. Check boxes are similar to radio buttons, but by convention their selection models are different. Any number of check boxes in a group -- none, some, or all -- can be selected. On the other hand, only one button can be selected from a group of radio buttons. The following figures show screenshots of two programs that use check boxes and radio buttons.

Figure 4: As you'd expect, the CheckBoxDemo application shows the use of check boxes, and the RadioButtonDemo application shows the use of radio buttons.

 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy