Working with Graphics |
To eliminate flashing, you must override theupdate()
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 ofupdate()
clears the Component's background before callingpaint()
. Because eliminating flashing requires that you eliminate all unnecessary drawing, your first step is always to reimplementupdate()
so that it doesn't clear the entire background unless it's necessary.Note: Even though your reimplementation of
update()
probably won't callpaint()
, you must still implement apaint()
method. The reason: When an area that your Component displays is suddenly revealed after being hidden (behind another window, for example), the AWT callspaint()
directly, without callingupdate()
. An easy way to implementpaint()
is to simply have it callupdate()
.Here is the code for a modified version of the previous example that implements
update()
to eliminate flashing. Here is the applet in action:
Here's the new version of the
paint()
method, along with the newupdate()
method. All of the drawing code that used to be in thepaint()
method is now in theupdate()
method. Significant changes in the drawing code are in bold font.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.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; } }
Working with Graphics |