The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Working with Graphics

Using Images

This is an image:

A picture of Duke.

The next few pages provide the details you'll need to work with images. You'll learn how to load, display, and manipulate them.


Wait!:  Although the API this section describes is valid for both JDK 1.1 and Java 2 (JDK 1.2), we recommend that you use Swing's built-in icon(in the Creating a GUI with JFC/Swing trail) support instead. If Swing icons aren't sufficient and you're writing a program for Java 2, then consider using the Java 2D API, which is described in the 2D Graphics(in the Creating a GUI with JFC/Swing trail) trail.

Support for using images is spread across the java.applet, java.awt, and java.awt.image packages. Every image is represented by a java.awt.Image object. In addition to the Image class, the java.awt package provides other basic image support, such as the Graphics drawImage methods, the Toolkit getImage methods, and the MediaTracker class. In java.applet, the Applet getImage methods make it easy for applets to load images using URLs. Finally, the java.awt.image package provides interfaces and classes that let you create, manipulate, and observe images.

Loading Images

The AWT makes it easy to load images in either of two formats: GIF and JPEG. The Applet and Toolkit classes provide getImage methods that work for either format. You use them like this:
myImage = getImage(URL); //in a method in an Applet subclass only
    or
myImage = Toolkit.getDefaultToolkit().getImage(filenameOrURL);
The getImage methods return immediately, so that you don't have to wait for an image to be loaded before going on to perform other operations in your program. While this improves performance, some programs require more control or information about image loading. You can track image loading status either by using the MediaTracker class or by implementing the imageUpdate method, which is defined by the ImageObserver interface.

This section will also tell you how to create images on the fly by using the MemoryImageSource class.

Displaying Images

It's easy to display an image using the Graphics object that's passed into your paintComponent method. You simply invoke a drawImage method on the Graphics object. For example:
g.drawImage(myImage, 0, 0, this);
This section explains the four forms of drawImage, two of which scale the image. Like getImage, drawImage is asynchronous, returning immediately even if the image hasn't been fully loaded or painted yet.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.