Previous | Next | Trail Map | Creating a User Interface | Working with Graphics


Eliminating Flashing: Overriding the update() Method

To eliminate flashing, you must override the update() method. The reason lies in the way the AWT requests that a Component (such as an Applet, Canvas, or Frame) repaint itself.

The AWT requests a repaint by calling the Component's update() method. The default implementation of update() clears the Component's background before calling paint(). Because eliminating flashing requires that you eliminate all unnecessary drawing, your first step is always to reimplement update() so that it doesn't clear the entire background unless it's necessary.

Note: Even though your reimplementation of update() probably won't call paint(), you must still implement a paint() method. The reason: When an area that your Component displays is suddenly revealed after being hidden (behind another window, for example), the AWT calls paint() directly, without calling update(). An easy way to implement paint() is to simply have it call update().

Here is the code for a modified version of the previous example that implements update() to eliminate flashing. Here is the applet in action:


Your browser can't run 1.0 Java applets. Here is a snapshot of what you'd see:


Here's the new version of the paint() method, along with the new update() method. All of the drawing code that used to be in the paint() method is now in the update() method. Significant changes in the drawing code are in bold font.

public void paint(Graphics g) {
    update(g);
}

public void update(Graphics g) {
    Color bg = getBackground();
    Color fg = getForeground();
    . . . /* same as old paint() method until we draw the rectangle
                if (fillSquare) {
                    g.fillRect(x, y, w, h);
                    fillSquare = false;
                } else { 
                    g.setColor(bg);
                    g.fillRect(x, y, w, h);
                    g.setColor(fg);
                    fillSquare = true;
                }
}
Note that since the background is no longer automatically cleared, the drawing code must now draw the non-black rectangles, as well as the black ones.


Previous | Next | Trail Map | Creating a User Interface | Working with Graphics