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

Displaying a Sequence of Images

The example in this section gives you the basics of displaying an image sequence. The next section has hints for improving the appearance and performance of this animation. This section shows only applet code. The code for an application would be similar, except you would use different code to load the images, as described in Loading Images.

Below are the ten images this applet uses.

T1.gif: The first of ten images that compose an animation of Duke waving. T2.gif: The second of ten images that compose an animation of Duke waving.T3.gif: The third of ten images that compose an animation of Duke waving.T4.gif: The fourth of ten images that compose an animation of Duke waving.T5.gif: The fifth of ten images that compose an animation of Duke waving.
T6.gif: Hi!T7.gif: The seventh of ten images that compose an animation of Duke waving.T8.gif: The eighth of ten images that compose an animation of Duke waving.T9.gif: The ninth of ten images that compose an animation of Duke waving.T10.gif: The final of ten images that compose an animation of Duke waving.

Here's a picture of what the applet looks like. Remember that you can click on the applet to stop or start the animation.

Click this figure to run the applet.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.

The code for this example, in ImageSequenceTimer.java(in a .java source file), is even simpler than for the previous example, which moved an image. Here is the code that differs significantly from the moving image example:

. . .//In initialization code:
Image[] images = new Image[10];
for (int i = 1; i <= 10; i++) {
    images[i-1] = getImage(getCodeBase(), "images/duke/T"+i+".gif");
}

. . .//In the paintComponent method:
g.drawImage(images[ImageSequenceTimer.frameNumber % 10],
            0, 0, this);
Another way to implement this example would be to use a label to display the image. Instead of having custom painting code, the program would use the setIcon method to change the image displayed.

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