Java Reference
In-Depth Information
ImageIcon Properties
Table 4-10 shows the six properties of
ImageIcon
. The height and width of the
ImageIcon
are the
height and width of the actual
Image
object. The
imageLoadStatus
property represents the results of
the loading of the
ImageIcon
from the hidden
MediaTracker
, either
MediaTracker.ABORTED
,
MediaTracker.ERRORED
, or
MediaTracker.COMPLETE
.
Table 4-10.
ImageIcon Properties
Property Name
Data Type
Access
description
String
Read-write
iconHeight
int
Read-only
iconWidth
int
Read-only
image
Image
Read-write
imageLoadStatus
int
Read-only
imageObserver
ImageObserver
Read-write
Sometimes, it's useful to use an
ImageIcon
to load an
Image
, and then just ask for the
Image
object from the
Icon
.
ImageIcon imageIcon = new ImageIcon(...);
Image image = imageIcon.getImage();
There is one major problem with using
ImageIcon
objects: They don't work when the
image and class file using the icon are both loaded in a JAR (Java archive) file, unless you explicitly
specify the full URL for the file within the JAR (
jar:http://www.example.com/directory/
foo.jar!/com/example/image.gif
). You can't just specify the file name as a
String
and let the
ImageIcon
find the file. You must manually get the image data first, and then pass the data
along to the
ImageIcon
constructor.
To help with loading images outside JAR files, Listing 4-4 shows an
ImageLoader
class that
provides a
public static Image getImage(Class relativeClass, String filename)
method.
You specify both the base class where the image file relative is found and the file name for the
image file. Then you just need to pass the
Image
object returned to the constructor of
ImageIcon
.
Listing 4-4.
Image Loading Support Class
import java.awt.*;
import java.io.*;
public final class ImageLoader {
private ImageLoader() {
}