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