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 overrideupdate()
so that it clears the entire background only when necessary. When moving drawing code from thepaint()
method toupdate()
, you might need to modify the drawing code so that it doesn't depend on the background being cleared.Note: Even if your implementation of
update()
doesn'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; } ...//same as old paint() method }Clipping the Drawing Area
One technique you might be able to use in yourupdate()
method is clipping the area you draw. This doesn't work for the example applet on this page, since the entire drawing area changes with every frame. Clipping works well, though, when only a small part of the drawing area changes -- such as when the user drags an object across a background.You perform clipping using the
clipRect()
method. An example of usingclipRect()
is in Improving the Appearance and Performance of Image Animation.
Working with Graphics |