update()
method.
By overriding the update()
method you can do all your painting in an offscreen Image
, and then just copy the final Image
onto the screen. Copying an image happens much more quickly and evenly than painting individual elements so there's no visible flicker.
The cookbook approach is simple. Add the following three private
fields to your applet and the public update()
method. Flicker will
magically disappear.
private Image offScreenImage;
private Dimension offScreenSize;
private Graphics offScreenGraphics;
public final synchronized void update (Graphics g) {
Dimension d = this.getSize();
if((this.offScreenImage == null) || (d.width != this.offScreenSize.width)
|| (d.height != this.offScreenSize.height)) {
this.offScreenImage = this.createImage(d.width, d.height);
this.offScreenSize = d;
this.offScreenGraphics = this.offScreenImage.getGraphics();
}
this.offScreenGraphics.clearRect(0, 0, d.width, d.height);
this.paint(this.offScreenGraphics);
g.drawImage(this.offScreenImage, 0, 0, null);
}