Previous | Next | Trail Map | Creating a User Interface (with Swing) | Using the JFC/Swing Packages

How to Use Icons

Some Swing components, such as JLabel and JButton, can be decorated with an icon -- a fixed-sized picture. In Swing, an icon is an object that adheres to the Icon(in the API reference documentation) interface. Swing provides a particularly useful implementation of the Icon interface: ImageIcon(in the API reference documentation), which paints an icon from a JPEG or GIF image.


Note to AWT Programmers: An ImageIcon object uses MediaTracker to load its image from a filename, URL, or other source. ImageIcon is a handy, easier-to-use alternative for Image because ImageIcon handles the relationship with the MediaTracker and keeps track of the loading status of the image so you don't have to. However, you can get the Image object from an ImageIcon if you need more control. See Using Images(in the Creating a User Interface trail) for more information about Image and MediaTracker.

Here's an applet that uses image icons for two different purposes:


Note: Because the preceding applet runs using Java Plug-in 1.1.1, it is a Swing 1.0.3 version of the applet. To run the Swing 1.1 Beta 3 version of the applet, you can use the JDK Applet Viewer to view IconDemoApplet.html, specifying swing.jar in the Applet Viewer's class path. For more information about running applets, refer to About Our Examples.
An image icon in a label implements the photograph area for the applet. The applet also uses image icons to decorate the Previous Picture and Next Picture buttons at the bottom of the applet window.

Try this:
  1. Run the applet.
    The applet above runs using Java Plug-in. If you prefer, you can run the applet with a browser or Applet Viewer that supports JDK 1.1 and Swing. Here's a file that contains the <APPLET> tag for running the IconDemoApplet.java applet. For information on running applets, see Running a Swing Applet.
  2. Push the Previous Picture and Next Picture buttons to view the photos.
  3. Hold the mouse over a photo. A tool tip appears that indicates the filename of the current photo and its width and height.
  4. To view your own photos, modify the applet parameters. You need to provide the name, caption, width, and height for each photo to be viewed. During initialization, the applet reads its parameters and stores the information in a vector of Photo objects.

Let's first look at the code from IconDemoApplet.java that creates and initializes the arrows used on the next and previous buttons because the code is very simple:
//create the image icons for the next and previous buttons
ImageIcon nextIcon = new ImageIcon(getURL("images/right.gif"));
ImageIcon previousIcon = new ImageIcon(getURL("images/left.gif"));
...
//use them to create a buttons
previous = new JButton("Previous Picture", previousIcon);
...
next = new JButton("Next Picture", nextIcon);
The single argument to the image icon constructor is the URL of the file containing the image. The getURL method appends the applet's code base to the name of the file containing the image for the icon. You can copy this method for use in your applets.
protected URL getURL(String filename) {
    URL codeBase = this.getCodeBase();
    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;
}
The ImageIcon class provides several other constructors for creating image icons from a byte array, an Image, or from a filename.

Now let's look at the code that loads the photo images:

//where the member variables are declared
Vector pictures;
...
	//early in the init method
        pictures = parseParameters();

	//create the image icon for the photo
	Photo first = (Photo)pictures.firstElement();
	ImageIcon icon = new ImageIcon(getURL(first.filename));
        first.setIcon(icon);
	...
This code creates a Vector of Photo objects (in the parseParameters method which is not shown). Each Photo object contains the name, caption, width, and height of the photo it represents, and after the picture's been displayed the first time, it's image icon. The image icon for the first photo is created in the init method of the applet and cached in the appropriate Photo object right away.

Image icons for the other photos get cached the first time the user views it. Here's the code from the buttons' actionPerformed method that determines if a picture has been viewed before. If not, the code creates a new image icon and caches it.

Photo pic = (Photo)pictures.elementAt(current);
icon = pic.getIcon();
if (icon == null) {
    icon = new ImageIcon(getURL(pic.filename));
    pic.setIcon(icon);
}
iconLabel.setText("");
iconLabel.setIcon(icon);
iconLabel.setToolTipText(pic.filename + ": " + icon.getIconWidth() +
			 " X " + icon.getIconHeight());
Why all the fuss about caching image icons? The program runs faster because image icons are created only once and the corresponding images are loaded only once. If you remove the explicit image icon caching from this program, a second viewing of a photo still appears to happen more quickly than the first. This implies that some implicit image caching is going on within the Java platform. However, this is a side-effect of the implementation and is not guaranteed.

The code also sets the photo's tool tip: The program calls ImageIcon's getIconWidth and getIconHeight methods to get information for the label's tool tip. The width and height provided by the image icon are more likely to be correct than those provided by the applet parameters.

The Icon API

The following tables list the commonly used ImageIcon constructors and methods. The API for using image icons falls into three categories:
Setting or Getting the Image Painted by the Image Icon
Method or Constructor Purpose

ImageIcon(byte[])
ImageIcon(byte[], String)
ImageIcon(Image)
ImageIcon(Image, String)
ImageIcon(String)
ImageIcon(String, String)
ImageIcon(URL)
ImageIcon(URL, String)
Create a ImageIcon instance, initializing it to contain the specified image. The first argument indicates the source -- image, byte array, filename, or URL -- from which the image icon's image should be loaded. The second argument, when present, provides a description for the image. The description is a short textual description of the image that could be used in a variety of ways, such as alternate text for the image.
void setImage(Image)
Image getImage()
Set or get the image displayed by the image icon.

Setting or Getting Information about the Image Icon
Method Purpose
void setDescription(String)
String getDescription()
Set or get a description of the image.
int getIconWidth()
int getIconHeight()
Get the size of the image icon.

Watching the Image Icon's Image Load
Method Purpose
void setImageObserver(ImageObserver)
ImageObserver getImageObserver()
Set or get an image observer for the image icon.
int getImageLoadStatus() Get the loading status of the image icon's image. The set of values returned by this method are defined by MediaTracker.

Examples that Use ImageIcon

The following table lists just a few of the many examples that use ImageIcon.

Example Where Described Notes
IconDemoApplet.java This page. An applet. Uses a label to show large images; uses buttons that have both images and text.
ButtonDemo.java How to Use Buttons Shows how to use icons in an application's buttons.
CheckBoxDemo.java How to Use Check Boxes Uses multiple JPEG images.
LabelDemo.java How to Use Labels Demonstrates using icons in an application's label, with and without accompanying text.
DialogDemo.java, CustomDialog.java, How to Make Dialogs Shows how to use standard icons in dialogs.
TreeIconDemo.java How to Use Trees Shows how to change the icons displayed by a tree's nodes.
ActionDemo.java How to Use Actions Shows how to specify the icon in a tool-bar button or menu item using an Action.


Previous | Next | Trail Map | Creating a User Interface (with Swing) | Using the JFC/Swing Packages