Double Buffering |
To create an applet that uses double-buffering, you need two things: an offscreen image to draw on and a graphics context for that image. Those two together mimic the effect of the applet's drawing surface: the graphics context (an instance of Graphics) to provide the drawing methods, such as drawImage and drawString, and the Image to hold the dots that get drawn.
There are four major steps to adding double-buffering to your applet.
Image offImage;
offImage = createImage(d.width, d.height);where d is a variable of type Dimension and corresponds to the dimensions of the applet.
public void update(Graphics g){ paint(g); }Actually you are overriding the update method which exists as default as part of any applet. Java automatically provides an update method for you if you don't define your own.
Graphics offGraphics = offImage.getGraphics();Now, whenever you have to draw to the screen, rather than drawing to paint's graphics, draw to the offscreen graphics. For example, to draw an image called img at position 10, 10, use the line:
offGraphics.drawImage(img, 10, 10, this);Next at the end of your paint method, after all the drawing to the offscreen image is done, add the following two lines to place the offscreen buffer on the real screen and to dispose of the Graphics object:
g.drawImage(offscreenImage, 0, 0, this); offGraphics.dispose();