Loading Images

Polygons, ovals, lines and text cover a lot of ground. The remaining graphic object you need is an image. Images in Java are bitmapped GIF or JPEG files that can contain pictures of just about anything. You can use any program at all to create them as long as that program can save in GIF or JPEG format.

Images displayed by Java applets are retrieved from the web via a URL that points to the image file. An applet that displays a picture must have a URL to the image its going to display. Images can be stored on a web server, a local hard drive or anywhere else the applet can point to via a URL. Make sure you put your images somewhere the person viewing the applet can access them. A file URL that points to your local hard drive may work while you're developing an applet, but it won't be of much use to someone who comes in over the web.

Typically you'll put images in the same directory as either the applet or the HTML file. Though it doesn't absolutely have to be in one of these two locations, storing it there will probably be more convenient. Put the image with the applet .class file if the image will be used for all instances of the applet. Put the applet with the HTML file if different instances of the applet will use different images. A third alternative is to put all the images in a common location and use PARAMs in the HTML file to tell Java where the images are.

If you know the exact URL for the image you wish to load, you can load it with the getImage() method:

URL imageURL = new URL("http://www.prenhall.com/logo.gif");
java.awt.Image img = this.getImage(imageURL);

You can compress this into one line as follows

Image img = this.getImage(new URL("http://www.prenhall.com/logo.gif"));

The getImage() method is provided by java.applet.Applet. The URL class is provided by java.net.URL. Be sure to import it.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified June 15, 1998