//
package widgets;
import java.awt.*;

public abstract class BufferedApplet extends java.applet.Applet implements Runnable
{
   abstract public void render(Graphics graphics);
   public boolean damage() { return damage; }

   Object lock = new Object();
   boolean isLocked = false;
   private Thread t;
   private int ticks = 0;
   public void init() { if (t == null) (t = new Thread(this)).start(); }
   public void start() { synchronized(lock) { lock.notifyAll(); isLocked = false; } }
   public void stop()  { isLocked = true; }
   public void run() {
      try {
         while (true) {
	      if (isLocked) synchronized(lock) { lock.wait(); }
            repaint();
	      t.sleep(30);
            ticks++;
         }
      } catch(InterruptedException e){};
   }

   private Rectangle r = new Rectangle(0,0,0,0);
   private Image bufferImage = null;
   protected Graphics bufferGraphics = null;
   public boolean damage = true;

   public void update(Graphics g) {
      if (r.width != bounds().width || r.height != bounds().height) {
         bufferImage    = createImage(bounds().width, bounds().height);
         bufferGraphics = bufferImage.getGraphics();
         r = bounds();
         damage = true;
      }
      if (damage())
         render(bufferGraphics);
      if (damage() || ticks % 30 == 0)
         if (bufferImage != null)
            g.drawImage(bufferImage,0,0,this);
      damage = false;
   }
}