Lab 6 Addendum
Lab 6 Addendum -- Implementing Double Buffering
Try the following to remove the flicker from your animation, by using double buffering. The updating of the screen will be done on an off-screen image, then transferred to the actual viewing window only when it is complete.
1. Add the following instance variables to Ballworld class definition:
private Image myImage;
private Graphics myOffscreenGraphics;
2. To create the offscreen image and get its graphics object, add the following lines at the very beginning of the init method:
myImage = createImage(getSize().width,getSize().height);
myOffscreenGraphics = myImage.getGraphics();
3. The paint method in the canvas object should first clear the offscreen graphics object and then notify all the balls to draw themselves on the offscreen graphics. When that is finished, the resulting image is drawn on the the actual graphics object used by the applet. You should also write an update method which just calls paint. This avoids having java itself clear the canvas when it is updated.
canvas = new Canvas (){
public void paint(Graphics g)
{
myOffscreenGraphics.setColor(Color.white);
myOffscreenGraphics.fillRect(0,0,getSize().width, getSize().height);
if(ballDispatcher != null)
ballDispatcher.notifyAll(myOffscreenGraphics);
g.drawImage(myImage,0,0,null);
}
public void update(Graphics g)
{
paint(g);
}
};