Double Buffering

--------------------------------------
Why use double-buffering? Without double-buffering applet animation often looks choppy. Double-buffering smooths this out by drawing to an offscreen image before tranferring the image to the visual screen.

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.

  1. Create an instance of the Image class to serve as your offscreen image. This is best done before the init() method like this:
       Image offImage;
    
  2. In the init method, create an Image object like this:
      offImage = createImage(d.width, d.height);
    
    where d is a variable of type Dimension and corresponds to the dimensions of the applet.
  3. Create an update method that looks like this:
      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.
  4. In the paint method you have to do a couple things. First, you create an instance of the Graphics class like this:
        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();
    
Let's review those four steps:
  1. Add instance variables to hold the image and graphics contexts for the offscreen buffer.
  2. Create an image and a graphics context when your applet is initialized
  3. Do all your applet painting to the offscreen buffer, not the applet's drawing surface.
  4. At the end of your paint method, draw the offscreen buffer to the real screen.



--------------------------------------
Assignment:
You will create an animation of a person doing pushups. You will need to draw three positions (up, middle, down) and cycle through them in the appropriate order to make it look like your person is really doing pushups.