How do I display an Image in an applet or application?

John Zukowski

The basic manner of displaying an Image in an applet/application is to call the drawImage() method of the Graphics class in the paint() method of the component to display the image. There are six varieties of the method that deal with scaling and background colors for transparent images. The basic manner of calling is as follows:

g.drawImage(image, xPosition, yPosition, this);

The last argument is what's called an ImageObserver and helps deal with the asynchronous loading of image data. Generally speaking, you just pass a reference to the applet as the image observer so that as more data is loaded the applet (the observer) is notified and redraws itself.

This leaves one question though. How do you get the image to display? The getImage() method of Applet or Toolkit helps here, requiring just the URL of where to get the image from:

Image image = getImage(url);

For an application, you would instead use getImage() method of Toolkit:

Toolkit kit = Toolkit.getDefaultToolkit();
Image image = kit.getImage(url);
Image image = kit.getImage(filename);

To make matters simpler for an applet, allowing you to move an applet between hosts without having to hardcode where the images come from, you can use a second variety of the method:

Image image = getImage(baseURL, file);

Here, you provide the base URL and filename separately. The two are combined to form the specific URL to get the image file from. How is this better? Well, there are two more methods to help here. The getDocumentBase() method allows you to start with a base URL of where the HTML file is located. And, the getCodeBase() method allows you to start with a base URL of where the .class file is located. Using one of the two you can find an image in the same directory as either with something like this:

Image image = getImage(getDocumentBase(), "image.jpg");

That is basically it, except if you want to package image files into a JAR. For this, you need to use the getResourceAsStream() method of the Class class.

InputStream in = getClass().getResourceAsStream
byte buffer[] = new byte[in.available()];
for (int i = 0, n = in.available(); i<n; i++)
  buffer[i] = (byte);
// this doesn't read all when reading from JAR
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.createImage(buffer);
Unfortunately, you cannot use the getResource() method (which returns a URL) as Netscape browsers do not support it.
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact