Removing Windoze Flicker

<< Poker Demo | Applets | Loading Image Files From Your jar >>

The flicker problem on Windows machines can be removed by doing two things:

  1. draw the graphics off-screen
  2. make a update() method that explicitly calls paint:
public void update(Graphics g)
    {
        paint(g); 
    }

To see the flicker, try removing the update() method and recompile on a windows machine

FlickerApplet.java

import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;


public class FlickerApplet extends Applet implements ActionListener
{
	public static final int WIDTH=400,HEIGHT=300;
	private int x, y;
	private Timer timer;
	private Image imgBuffer;
    private Graphics gBuffer;
    private Font font;
    /**
     * imgBuffer is the "off screen" graphics area
     * gBuffer is imgBuffer's graphics object 
     * which we need to draw stuff on the image
     */
    public void init()
    {    	    
        imgBuffer = createImage(WIDTH,HEIGHT);
        gBuffer = imgBuffer.getGraphics();

        //Here we make a timer event every 60 millisecs
        timer = new Timer(60,this);
        timer.start();
		x = this.getWidth()/2;
		y = this.getHeight()/2;
        font = new Font("Helvetica", Font.BOLD,  18);       
	}
    public void paint(Graphics g)
    { 
    		// draw components off screen on gBufffer
    	   gBuffer.setColor(Color.RED);
    	    gBuffer.fillRect(0, 0, WIDTH, HEIGHT);
    	    gBuffer.setColor(Color.BLACK);
    	    gBuffer.setFont(font);
    	    gBuffer.drawString("X = "+x, 20, 40);
    		gBuffer.fillOval(x, y, 50, 50);
    		// now we quickly swap the screen image with the one we made
    		g.drawImage(imgBuffer,0,0,this);
    }
    /**
     * update is only needed for Microsoft Windows 
     * to remove the famous "flicker problem"
     */
    public void update(Graphics g)
    {
        paint(g); 
    }
    /**
     * Here we implement the ActionLister interface.
     * Our time produced an action event over the
     * passage of time.  So to animate our applet
     * we change the horizontal location of out Oval.
     */
	@Override
	public void actionPerformed(ActionEvent e) {
		x+=3;
		x=x%(WIDTH-50);	
		repaint();
	}
}