import java.awt.Frame; 
import java.awt.Graphics; 
import java.awt.Image;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.applet.Applet; 

public class Test extends Applet 
                  implements WindowListener, MouseMotionListener {

    private Image    bufimg = null;
    private Graphics bufgrf = null;

    public static void main(String[] args) {
        Frame F=new Frame("Refreshing from the Buffered Drawing");
        Test BD=new Test();
        F.setSize(800, 600);
        F.setResizable(false); 
        // must not resize due to the fixed buffer size
        F.add(BD);
        F.setVisible(true);
        // set visible must be true before init()
        // to allow drawing in createImage(...)
        BD.init();
        BD.start();
        F.setVisible(true);
        // and once again in case one added any GUI components
        F.addWindowListener(BD);
    }

    public void init() {
        bufimg = createImage(getWidth(),getHeight());
        bufgrf = bufimg.getGraphics();
    }

    public void start() {
        addMouseMotionListener(this);
    }

    public void paint(Graphics g) {
        // updating it in a flush
        if (bufimg!=null)
            g.drawImage(bufimg,0,0,this);
        // doubelcheck against null in case paint is called before
        // you initialize OffScreenImage - it can be called by OS!
    }

    public void stop() { }


    // INTERFACE WindowListener -------
    public void windowClosing(WindowEvent e)      { stop(); System.exit(0); }
    public void windowClosed(WindowEvent e)       {  }
    public void windowOpened(WindowEvent e)       {  }
    public void windowIconified(WindowEvent e)    {  }
    public void windowDeiconified(WindowEvent e)  {  }
    public void windowActivated(WindowEvent e)    {  }
    public void windowDeactivated(WindowEvent e)  {  }

    // INTERFACE MouseMotionListener -------
    public void mouseMoved(MouseEvent e)          {
        Graphics g=this.getGraphics();
        if (lastx!=-1) bufgrf.clearRect(lastx,lasty, 200,200);
        lastx=e.getX();
        lasty=e.getY();
        bufgrf.fillRect(lastx,lasty, 200,200);
        g.drawImage(bufimg,0,0,this);
    }
    public void mouseDragged(MouseEvent e)        {}

    int lastx = -1;
    int lasty = -1;
}