Reducing Flicker


Double Buffering: You may have noticed that there was a significant amount of flicker in the applets you've worked on in this unit up to this point. This can be reduced through a technique known as double buffering. In double buffering the screen update is rendered in an off screen buffer and then the entire buffer is drawn on screen at one time. Here are the basic steps necessary to implement double buffering:

  1. Create instances of Image and Graphics
  2. Initialize Image variable
  3. Create an update method which calls paint
  4. Initialize Graphics variable
  5. Draw to off screen image
  6. Render off screen image
  7. Dispose of off screen graphics
import java.awt.*; import java.awt.event.*; import java.applet.*; import java.util.*; public class flick extends Applet{ //1. Create instances of Image and Graphics: Image offI; Graphics offG; int x; //distance from center; int Xcenter; // x coordinate for center int Ycenter; // y coordinate for center Dimension d; public void init(){ setBackground(Color.white); d=getSize(); x=10; Xcenter=d.width/2; Ycenter=d.height/2; //2. Initialize Image variable offI=createImage(200,200); requestFocus(); this.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent k){ x+=5; if(x>100) x=10; repaint(); } }); } //3. Create an update method which calls paint public void update(Graphics g){ paint(g); } public void paint(Graphics g){ //4. Initialize Graphics variable offG=offI.getGraphics(); //5. Draw to off screen image offG.setColor(Color.white); offG.fillRect(0,0,d.width, d.height); offG.setColor(Color.red); offG.drawRect(1,1,d.width-2, d.height-2); offG.setColor(Color.blue); offG.fillOval(Xcenter-x-6, Ycenter-3, 6, 6); offG.fillOval(Xcenter+x, Ycenter-3, 6, 6); offG.fillOval(Xcenter-3, Ycenter-x-6, 6, 6); offG.fillOval(Xcenter-3, Ycenter+x, 6, 6); //6. Render off screen image g.drawImage(offI,0,0,this); //7. Dispose of off screen graphics offG.dispose(); } }

ASSIGNMENT: Your job is first of all to get this sample applet up and running. Then you need to add the red lines.