1  /*
  2   * Double-buffered version of mRectApplet.java
  3   */
  4  
  5  import java.applet.*;
  6  import java.awt.*;
  7  
  8  public class mObjApplet extends Applet implements Runnable {
  9  
 10    // Instance variables:
 11    int numObj = 3;     // number of objects
 12    mPoint object[];    // object array
 13    Thread thread;      // a thread
 14    Image image;        // for double buffering
 15      
 16    // Class method:
 17    public void initObjects() {
 18      /* initialize object array */
 19      object = new mPoint[numObj];
 20      /* initialize a rectangle */
 21      object[0] = new mRectangle(10, 10, 100, 100);
 22      object[0].setDelta(1, 1);
 23      object[0].setColor(Color.red);
 24      /* initialize a circle */
 25      object[1] = new mCircle(200, 10, 100, 100);
 26      object[1].setDelta(-1, 1);
 27      object[1].setColor(Color.blue);
 28      /* initialize a triangle */
 29      object[2] = new mTriangle(10, 200, 100, 100);
 30      object[2].setDelta(-1, 1);
 31      object[2].setColor(Color.green);
 32      image = createImage(size().width, size().height);
 33    }
 34  
 35    // Override java.applet.Applet.init:
 36    public void init () {
 37      initObjects();
 38    }
 39  
 40    // Override java.applet.Applet.start:
 41    public void start() {
 42      if (thread == null) {
 43        // Reinitialize:
 44        initObjects();
 45        thread = new Thread(this);
 46        thread.start();
 47      }
 48    }
 49    
 50    // Override java.applet.Applet.stop:
 51    public void stop() {
 52      if (thread != null) {
 53        thread.stop();
 54        thread = null;
 55      }
 56    }
 57    
 58    // Implement java.lang.Runnable.run:
 59    public void run() {
 60      while(thread != null) {
 61        // repaint() invokes update():
 62        repaint();
 63        try {
 64          Thread.sleep(20);
 65        } 
 66        catch(InterruptedException e) {
 67          // Do nothing   
 68        };
 69      }
 70    }
 71  
 72    // Override java.awt.Component.update:
 73    public void update(Graphics g) {
 74      /* Get Off Screen Graphics Context */
 75      Graphics og = image.getGraphics(); 
 76      /* fill background */
 77      og.setColor(getBackground());
 78      og.fillRect(1, 1, size().width-2, size().height-2);
 79      /* draw boundry */
 80      og.setColor(getForeground());
 81      og.drawRect(0, 0, size().width-1, size().height-1);
 82      /* move object */
 83      for (int i=0; i<numObj; i++) {
 84        object[i].checkBoundary(bounds());
 85        object[i].move(og);
 86      }
 87      /* user who call getGraphics should call dispose */
 88      og.dispose();
 89      g.drawImage(image, 0, 0, this);
 90    }
 91    
 92    // Override java.awt.Component.paint:
 93    public void paint(Graphics g) {
 94      update(g);
 95    }
 96    
 97  }