The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Using Swing Components

How to Make Applets

This section covers JApplet -- a class that enables applets to use Swing components. JApplet is a subclass of java.applet.Applet(in the API reference documentation), which is covered in the Writing Applets(in the Creating a GUI with JFC/Swing trail) trail. If you've never written a regular applet before, we urge you to read that trail before proceeding with this section. The information provided in that trail applies to Swing applets, with a few exceptions that this section explains.

Any applet that contains Swing components must be implemented with a subclass of JApplet(in the API reference documentation). Here's a Swing version of one of the applets that helped make Java famous -- an applet that animates our mascot, Duke, doing cartwheels:

Click this figure to run the applet.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.

You can find the main source code for this applet in TumbleItem.java(in a .java source file). You will also need one other source file and the image files that compose the animation. See the examples index for links to all the files required by this example.

This section discusses the following topics:

Features Provided by JApplet

JApplet adds two major features to the functionality that it inherits from java.applet.Applet. First, Swing applets provide support for assistive technologies(in the Creating a GUI with JFC/Swing trail). Second, because JApplet is a top-level Swing container, each Swing applet has a root pane. The most noticeable results of the root pane's presence are support for adding a menu bar and the need to use a content pane.

As described in Using Top-Level Containers, each top-level container such as a JApplet has a single content pane. The content pane makes Swing applets different from regular applets in the following ways:


JDK 1.1 Note:  If you run a Swing applet using JDK 1.1 and JFC 1.1, then you might see an error message that looks like this:
Swing: checked access to system event queue.
You can often avoid this message by telling the applet not to check whether it has access to the system event queue. To do so, put the following code in the constructor for the applet class:
getRootPane().putClientProperty(
                  "defeatSystemEventQueueCheck",
                  Boolean.TRUE);

Threads in Applets

Because applets inherently use multiple threads and Swing components aren't thread safe, you should take care with threads in Swing applets. It's generally considered safe to create and manipulate Swing components directly in the init method. However, the other milestone methods -- start, stop, and destroy -- might cause trouble when the browser invokes them after the applet's already visible. To avoid trouble, you should make these methods thread safe.

For example, when you implement a stop or start method, be aware that the browser doesn't call them from the event-dispatching thread. Thus, those methods shouldn't affect or query Swing components directly. Instead, they should use techniques such as using the SwingUtilities.invokeLater method to affect components.

For more information about using threads, see Threads and Swing(in the Creating a GUI with JFC/Swing trail) and How to Use Threads(in the Creating a GUI with JFC/Swing trail).

Using Images in a Swing Applet

The Applet class provides the getImage method for loading images into an applet. The getImage method creates and returns an Image object that represents the loaded image. Because Swing components use Icons rather than Images to refer to pictures, Swing applets tend not to use getImage. Instead Swing applets create instances of ImageIcon--an icon loaded from an image file. ImageIcon comes with a code-saving benefit: it handles image tracking automatically. Refer to How to Use Icons(in the Creating a GUI with JFC/Swing trail) for more information.

The animation of Duke doing cartwheels requires 17 different pictures. The applet uses one ImageIcon per picture and loads them in its init method. Because images can take a long time to load, the icons are loaded in a separate thread implemented by a SwingWorker object(in the Creating a GUI with JFC/Swing trail). Here's the code:

public void init() {
    ...
    imgs = new ImageIcon[nimgs];
    final SwingWorker worker = new SwingWorker() {
        public Object construct() {
            URL baseURL = getCodeBase();
            String prefix = dir + "/T";
    
            //Images are numbered 1 to nimgs,
            //but fill array from 0 to nimgs-1
            for (int i = 0; i < nimgs; i++) {
                imgs[i] = new ImageIcon(getURL(baseURL,
                                               prefix + (i+1)
                                               + ".gif"));
            }
            finishedLoading = true;
            timer.start(); //Start the animation.
            return imgs;
        }
        ...
    };
    worker.start();
    ...
}
To create an ImageIcon and load it with an image, you specify the image file's URL to the ImageIcon's constructor. The getURL method is implemented as follows:
protected URL getURL(URL codeBase, String filename) {
    URL url = null;

    try {
        url = new URL(codeBase, filename);
    } catch (java.net.MalformedURLException e) {
        System.out.println("Couldn't create image: "
                           + "badly specified URL");
        return null;
    }

    return url;
}

Providing an OBJECT/EMBED Tag for Java Plug-in

To run, an applet must be included in an HTML page. If your applet's users have Swing-enabled browsers, then you can include the applet in an HTML page with an <APPLET> tag. Here's the <APPLET> tag for the cartwheeling Duke applet:
<applet code="TumbleItem.class" 
        codebase="example-swing/"
        archive="tumble.jar"
        width="600" height="95">
    <param name="maxwidth" value="120">
    <param name="nimgs" value="17">
    <param name="offset" value="-57">
    <param name="img" value="images/tumble">

Your browser is completely ignoring the &lt;APPLET&gt; tag!

</applet>
To find out about the various <APPLET> tag parameters, refer to Test Driving an Applet(in the Creating a GUI with JFC/Swing trail) and Using the APPLET Tag(in the Creating a GUI with JFC/Swing trail).

If your applet's users don't have a Swing-enabled browser, then they'll need to use Java Plug-in to run the applet. Java Plug-in requires that an applet be included in an HTML page with an <OBJECT> tag or <EMBED> tag. You can download a free tool that automatically generates the necessary tags from an <APPLET> tag. To download Java Plug-in and the HTML conversion tool, and for related documentation, go to the Java Plug-in home page(outside of the tutorial) .

Because Plug-in can take a while to download and load into the browser, it's considerate to give users advance warning that a page contains an applet. You might have noticed that the tutorial's applets don't run the same page as the text that describes the applet. Instead, we provide a screenshot of the applet running and a link that brings up a separate browser window in which to run the applet. This provides a better experience because they can choose whether or not to visit a page that contains an applet.

The JApplet API

The next table lists the interesting methods that JApplet adds to the applet API. They give you access to features provided by the root pane. Other methods you might use are defined by the Component(in the API reference documentation) and Applet(in the API reference documentation) classes. See Component Methods for a list of commonly used Component methods, and Taking Advantage of the Applet API(in the Creating a GUI with JFC/Swing trail) for help in using Applet methods.

Method Purpose
void setContentPane(Container)
Container getContentPane()
Set or get the applet's content pane. The content pane contains the applet's visible GUI components and should be opaque.
JRootPane createRootPane()
void setRootPane(JRootPane)
JRootPane getRootPane()
Create, set, or get the applet's root pane. The root pane manages the interior of the applet including the content pane, the glass pane, and so on.
void setJMenuBar(JMenuBar)
JMenuBar getJMenuBar()
Set or get the applet's menu bar to manage a set of menus for the frame.
void setGlassPane(Component)
Component getGlassPane()
Set or get the applet's glass pane. You can use the glass pane to intercept mouse events.
void setLayeredPane(JLayeredPane)
JLayeredPane getLayeredPane()
Set or get the applet's layered pane. You can use the frame's layered pane to put components on top of or behind other components.

Applet Examples

This table shows examples of Swing applets and where those examples are described.

Example Where Described Notes
TumbleItem This page An animation applet
HelloSwingApplet Running Swing Applets(in the Creating a GUI with JFC/Swing trail) The simplest of all Swing applets -- it contains only a label.
AppletDemo Running Swing Applets(in the Creating a GUI with JFC/Swing trail) The applet version of the button demo program. Can be run either as an application or as an applet.
IconDemoApplet How to Use Icons(in the Creating a GUI with JFC/Swing trail) An applet for showing photos.
Several examples. Using Layout Managers(in the Creating a GUI with JFC/Swing trail) You can run several applets from the page listed. Each applet demonstrates a different layout manager.
Several examples. Some Simple Event-Handling Examples(in the Creating a GUI with JFC/Swing trail) You can run several applets from the page listed. Each applet shows how to handle different types of events.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.