Prev Up
Go backward to Interface Components
Go up to Top

Images

One mechanism in Java that can provide great flexibility in creating an interesting graphic display is the ability to access images stored as ".gif" and ".jpeg" files on the web and draw them at desired positions within the applet's screen region.

The primitives to draw images are actually associated with the "pen". We did not include a discussion of image drawing with our discussion of the other drawing primitives, however, because image drawing requires the use of a distinct class of objects, the "Image" class.

The first step in using an image within an applet is to instruct the applet to load the image from some location on the web. This is done by providing the URL for the image as a string parameter to the "getImage" method. The "getImage" method returns an object of the "Image" class which can then be passed as a parameter to a drawing method when we want the image displayed. To do this, the object returned by "getImage" must usually be associated with an instance variable name.

The declaration of a name to be used for an image would look like:

Image prettyPicture;
Given that such a variable has been declared, instructions like:
prettyPicture = getImage("sunset.gif");
and
prettyPicture = getImage("http://www.someplace.net/imagedirectory/a9924.jpeg");
might be used to actually fetch images. (The first URL shown would be interpreted relative to the folder from which the web page containing the applet was loaded.)

Loading an image through the web can be a time consuming process. In particular, it is not the sort of thing one wants to do in response to a mouse click since an applet should react quickly to such user input. As a result, the "loadImage" method should only be invoked from within an applet's "begin" method.

  • Working with Images

  • Prev Up