Purpose:
The purpose is to reduce the flicker that is sometimes associated with animation in Java.
Method:
Draw the image you want created in RAM, not on the screen. Then do a high speed copy from the RAM onto the screen.
Advantages:
Much less flicker, especially for complex images
Disadvantages:
Requires about 10 lines more code.
Slows the overall frame rate.
How to Double Buffer:
1) You
need to create a place in RAM to store the temporary image. Use this line
Image offi;
offi = createImage*(400,400);
2) You
need to get a ‘graphics’ for that image.
Graphics offg;
offg = offi.getGraphics();
3) In
paint, don’t draw to the screen.
Instead, draw to the image you just created, using the graphics you just
made. For example, to draw a rectangle you
might
offg.drawRect(10,10,30,50);
4) As
the last step of paint, copy the image you’ve made onto the screen.
g.drawImage(offi, 0, 0,
this);
5) Normally,
paint clears the screen before it allows you to draw. With double-buffering there is no need to
clear the screen. You can make things
quicker by telling Java to not bother with screen clearing. Creating an ‘update’ function that calls
paint without clearing the screen is how one does this.
public void update(Graphics g)
{
paint(g);
}
6) You’re done. It works. Yea!