Swing: A Very Brief Overview
AAHC

Click on A to make all fonts on the page smaller.

Click on A to make all fonts on the page larger.

Click on HC to toggle high contrast mode. When you move your mouse over some bold words in high contrast mode, related words are automatically highlighted. Text is shown in black and white.


AWT vs. Swing

This lesson will give you a brief overview of the Swing package, and in particular, compare the AWT package to the Swing package. The similarities between the components of these two packages will allow you to assimilate the new material and ultimately incorporate more options to control the appearance of your GUI.

According to the freejavaguide.com page on Java Swing: Free Java Tutorials:

Java Swing is a GUI toolkit for Java. Swing is one part of the Java Foundation Classes (JFC). Swing includes graphical user interface (GUI) widgets such as text boxes, buttons, split-panes, and tables.

Swing widgets provide more sophisticated GUI components than the earlier Abstract Window Toolkit. Since they are written in pure Java, they run the same on all platforms, unlike the [first] AWT which is tied to the underlying platform's windowing system. Swing supports pluggable look and feel – not by using the native platform's facilities, but by roughly emulating them. This means you can get any supported look and feel on any platform. The disadvantage of lightweight components is possibly slower execution. The advantage is uniform behavior on all platforms.

NotePlease note, where possible, we have updated our links to point to the new Oracle site for Java. Oracle bought Sun Microsystems some time ago. Some of Oracle's links point to locations that no longer exist. We have no contol over that. We are sorry for any inconvenience. If you are directed to the java.sun.com domain from our course, it is because we could not find a corresponding oracle.com URL for that particular resource. Oracle has indicated that they want to shut down java.sun.com; however, they have, at least for the time being, delayed that decision, partly due to outcry from the Java community.
HelloWorld in AWT and Swing

To illustrate the similarities between AWT and Swing, we'll use a HelloWorld Frame and JFrame. Later we'll use a HelloWorld JApplet, which makes use of Threads. Create a new java4_Lesson2 project. If you're given the option to "Open Associated Perspective", click No.

In your new project, create a HelloAppAWT class as shown:

Type HelloAppAWT as shown in blue:

CODE TO TYPE: HelloAppAWT
package compare;

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

public class HelloAppAWT extends Frame {
    public HelloAppAWT() {
        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){ 
                System.exit(0);
        }});
        add(new Label("Hello, world!"));
        pack();
    }

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

Save and run it.

Now we'll write the small application in Swing. In the comments, you can see how it differs from AWT.

In the java4_Lesson2 project, add the HelloAppSwing class as shown:

Type HelloAppSwing as shown in blue below:

CODE TO TYPE: HelloAppSwing
package compare;

import javax.swing.*; 

public class HelloAppSwing extends JFrame {
    public HelloAppSwing() {
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        add(new JLabel("Hello, world!"));
        pack();
    }

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

Save and run it.

Let's take a look at the import in our Swing example. The first line imports only the main Swing package: import javax.swing.* This is the only package that your application needs. However, if your application had any Listeners (for user input), your Swing program might have also needed to import the AWT packages java.awt.* and java.awt.event.*. These packages are often required because Swing components use the AWT infrastructure, including the AWT event model as well. They use the same Listeners and Listener API Tables.

Changing Appearance

Even though the differences in appearance are often subtle, you'll still want to control what your GUI's look like. You can use any of these four platform types:

The Swing tutorial has an example of a more decked out GUI. It is replicated exactly here so that you can see the comments and the copyright notice as well (you don't need to type the copyright notice though).

In the java4_Lesson2 project, add a HelloWorldSwing class as shown:

Type HelloWorldSwing as shown in blue below:

CODE TO TYPE: HelloWorldSwing

package compare;

import javax.swing.*;      

public class HelloWorldSwing {
    /**
     * Create the GUI and show it.  For thread safety, this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add the "Hello World" label.
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Save and run it. You might need to resize the window. Now, THAT looks different.

Go to the javax.swing.JFrame class in the API. Look at the setDefaultLookAndFeelDecorated() method. Click on it to see the detailed description, and read the discussion of the LookAndFeel.

To learn more about LookAndFeel for JFrames, see How to Make Frames (Main Windows), Using Swing Components, and also the page on Pluggable Look and Feel.

JApplets, JFrames, and Threads

So, what was going on with the main() method and javax.swing.SwingUtilities.invokeLater() call with the Runnable interface parameter?

In our first examples with the AWT and Swing applications, we did not use a Runnable interface to access another thread from our main() method. This can lead to race conditions in the class's constructors and/or init() methods.

Because of these differences between the Swing and the AWT packages, Oracle suggests making JFrames for applications and JApplets differently.

More Information on Applets

Oracle's Swing Tutorial link, How to Make Applets, is really useful:

Because so much of the Swing material uses the AWT infrastructure and event model, the tutorial first points to a tutorial for Getting Started with Applets.

Back on the How to Make Applets page, we have the link, Features Provided by JApplet, which shows us how to add components to the Content Pane. Go ahead and read this whole page to become familiar with the tools and concepts there.

The ContentPane is a Container that works similarly to the way double-buffering does when we paint on the Graphics area in applets. In the same way that the setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) handles the Window listener for you, the ContentPane will take care of double-buffering for you and help graphics run more smoothly.

Applets aren't much different from applications. The main difference between them is in the ways they are started and in the way you produce a GUI for an application. In order to have a GUI for an application, you need to instantiate the Frame (or JFrame).

Let's compare the two. Go back to the How to Make Applets page, then to the section Threads in Applets. It has an example of an init() method that looks a lot like the main() method of their JFrame application.

Now go to javax.swing.SwingUtilities and read over the full description of the invokeLater(Runnable doRun) method.

More Information on JApplets

We'll demonstrate JApplets using the example methods init() and createGUI()) from the Swing tutorial How to Make Applets.

In the java4_Lesson2 project, add a SwingAppletDemo class as shown:

Type SwingAppletDemo as shown in blue below:

CODE TO TYPE: SwingAppletDemo
package compare;

import javax.swing.*; // Change from javax.swing.JApplet
import java.awt.*;

public class SwingAppletDemo extends JApplet {
    public void init() {
        //Execute a job on the event-dispatching thread:
        //creating this applet's GUI.
        try {
            javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    createGUI();
                }
            });
        } catch (Exception e) {
            System.err.println("createGUI didn't finish successfully");
        }
    }

    private void createGUI() {
        JLabel label = new JLabel("You are successfully running a Swing applet!");
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.black));
        getContentPane().add(label, BorderLayout.CENTER);
    }
}

Save and run it (you might need to resize the Applet window).

Our example JApplet code shows two methods: init() and createGUI(). These methods are similar to the application's main() and createAndShowGUI() methods; starting JApplets is very similar to starting applications. But the JApplet's init() method with its javax.swing.SwingUtilities.invokeAndWait() call, is different from the application's javax.swing.SwingUtilities.invokeLater() call.

The invokeLater method is not appropriate for some JApplets because it could allow init() to return before initialization is complete. This could cause applet problems that are difficult to debug (such as constructors that mistakenly have a return type).

Take a look at the class LabelDemo.java (from How to Use Labels), which extends JPanel. main() invokes createAndShowGUI(), which instantiates a JFrame, then adds a LabelDemo (which is a JPanel), then gives the frame the ContentPane of this JPanel. LabelDemo's constructor adds all of the components to the JPanel.

Here's an example that's a bit more complex: IconDemoApp (from Icon Demo), and an application. While we're at it, here's the Table of Examples for a tutorial on Swing Components.

Even More Swing

Explore on your own. Have fun--Swing has some awesome looks and capabilities! Here are a few more resources for you:

Finally, check out the Swing Set Demo. You can test it from this web page or, if you downloaded Java and the demos on to your own machine, you have Swing Set Demo in the java directory. Play around with this demo, all it takes is a few mouse clicks!

We still have a lot more Swing coming up in the next lesson. See you there!