Using the JFC/Swing Packages |
Some Swing components, such asJLabel
andJButton
, can be decorated with an icon -- a fixed-sized picture. In Swing, an icon is an object that adheres to theIcon
interface. Swing provides a particularly useful implementation of theIcon
interface:ImageIcon
, which paints an icon from a JPEG or GIF image.
Note to AWT Programmers: AnImageIcon
object usesMediaTracker
to load its image from a filename, URL, or other source.ImageIcon
is a handy, easier-to-use alternative forImage
becauseImageIcon
handles the relationship with theMediaTracker
and keeps track of the loading status of the image so you don't have to. However, you can get theImage
object from anImageIcon
if you need more control. See Using Images for more information aboutImage
andMediaTracker
.
Here's an applet that uses image icons for two different purposes:
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.
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 viewIconDemoApplet.html
, specifyingswing.jar
in the Applet Viewer's class path. For more information about running applets, refer to About Our Examples.Let's first look at the code from
Try this:
- 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 theIconDemoApplet.java
applet. For information on running applets, see Running a Swing Applet.- Push the Previous Picture and Next Picture buttons to view the photos.
- Hold the mouse over a photo. A tool tip appears that indicates the filename of the current photo and its width and height.
- 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.
IconDemoApplet.java
that creates and initializes the arrows used on the next and previous buttons because the code is very simple:The single argument to the image icon constructor is the URL of the file containing the image. The//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);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.Theprotected 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; }ImageIcon
class provides several other constructors for creating image icons from a byte array, anImage
, or from a filename.Now let's look at the code that loads the photo images:
This code creates a//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); ...Vector
ofPhoto
objects (in theparseParameters
method which is not shown). EachPhoto
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 theinit
method of the applet and cached in the appropriatePhoto
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.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.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());The code also sets the photo's tool tip: The program calls
ImageIcon
'sgetIconWidth
andgetIconHeight
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 usedImageIcon
constructors and methods. The API for using image icons falls into three categories:
- Setting or Getting the Image Painted by the Image Icon
- Setting or Getting Information about the Image Icon
- Watching the Image Icon's Image Load
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 useImageIcon
.
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
.
Using the JFC/Swing Packages |