Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Working with Graphics

Animating Graphics

This page features an example applet that creates a moving a checkerboard effect by painting alternate squares. The squares are drawn by the Graphics fillRect() method. Here's the applet in action:


Your browser can't run 1.0 Java applets, so here is a snapshot of what you'd see.

You might notice that the graphics aren't animated perfectly smoothly -- that occasionally part or all of the drawing area flashes noticeably. The next page will explain the cause of this flashing and tell you how to eliminate it.

Here is the applet code. The major difference between it and the animation template is that the paint() method has changed to draw filled rectangles, using an algorithm that depends on the current frame number. This applet also introduces a couple of instance variables, one that holds the square size and another that keeps track of whether the next column to be drawn begins with a black square. The user can set the square size by means of a new applet parameter.

Below is the paint() code that performs the actual drawing. Note that the program draws only the black boxes (indicated by fillSquare being true), not the other boxes. It can get away with this because, by default, a Component's drawing area is cleared (set to the background color) just before the paint() method is called.

// Draw the rectangle if necessary.
if (fillSquare) {
    g.fillRect(x, y, w, h);
    fillSquare = false;
} else {
    fillSquare = true;
}


Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Working with Graphics