Java Graphics  «Prev  Next»

Lesson 6 Loading and drawing images
Objective Loading and drawing images
Foreward to the AWT: The AWT was used with Java 1.0 and Java 1.1. The successor technologies to Java AWT are 1) Java Foundation Classes and 2) JavaFX

Loading and Drawing Images

Before you can draw an image you must first load it into memory. This step is necessary because images are typically stored in files, and you must first load the contents of an image file into memory before you can draw the image.
To load an image, you use one of the getImage() methods defined in the Applet class:
This getImage() method takes a URL parameter that should include the filename of the image to be loaded.

public Image getImage(URL url)

This version of getImage() allows you to specify an image filename separated from its base URL.

public Image getImage(URL url, String name)

I recommend using the second version of getImage() because there is another handy method you can use to obtain the base URL for an image:

Image img = getImage(getCodeBase(), "Spider.gif");

The getCodeBase() method gets the URL of the applets directory. So, the example code shows how to load an image named Spider.gif from the applet directory.