1  /* File:  mRectApplet.java */
  2  
  3  import java.awt.*;
  4  import java.applet.*;
  5  
  6  public class mRectApplet extends Applet implements Runnable 
  7   {
  8    // Instance variables:
  9    private Thread thread;
 10    private mPoint object[] = new mPoint[2];
 11    private int x[] = { 10, 200 };  // initial x coordinates
 12    private int y[] = { 10,  10 };  // initial y coordinates
 13  
 14  
 15    // Override java.applet.Applet.init:
 16    public void init () 
 17    {
 18      setBackground( Color.black );
 19  
 20      object[0] = new mRectangle( x[0], y[0], 100, 100 );
 21      object[0].setDelta( 1, 1 );
 22      object[0].setColor( Color.red );
 23      
 24      object[1] = new mRectangle( x[1], y[1], 100, 100 );
 25      object[1].setDelta( -1, 1 );
 26      object[1].setColor( Color.blue );
 27    }
 28  
 29    // Override java.applet.Applet.start:
 30    public void start() 
 31    {
 32      if ( thread == null ) 
 33      {
 34        // Reinitialize (x,y) coordinates:
 35        object[0].setPoint( x[0], y[0] );
 36        object[1].setPoint( x[1], y[1] );
 37  
 38        // Start a new thread:
 39        thread = new Thread( this );
 40        thread.start();
 41      }
 42    }
 43  
 44    // Override java.applet.Applet.stop:
 45    public void stop() 
 46    {
 47      if ( thread != null ) 
 48      {
 49        thread.stop();
 50        thread = null ;
 51      }
 52    }
 53  
 54    // Implement java.lang.Runnable.run:
 55    public void run() 
 56    {
 57      while ( thread != null ) 
 58     {
 59        repaint();
 60        try 
 61        { Thread.sleep(20);
 62        } catch ( InterruptedException e ) 
 63        {   };         // Do nothing  
 64      }
 65     }
 66  
 67    // Override java.awt.Component.paint:
 68    public void paint( Graphics g ) 
 69    {
 70      // Move each object and then paint it:
 71      for ( int i = 0; i < object.length; i++ ) 
 72           { object[i].move(); object[i].paint(g); }
 73    }
 74  }
 75