1 /* 2 * File: MovingPolygons.java 3 * 4 * Moving polygons with boundary checking 5 * 6 * Copyright: Northeast Parallel Architectures Center 7 * 8 */ 9 10 import java.applet.Applet; 11 import java.awt.*; 12 13 public class MovingPolygons extends Applet implements Runnable { 14 15 // Instance variables: 16 private final int numPoly = 3; // number of drawable polygons 17 private MovablePolygon polygon[]; // array of drawable polygons 18 private Thread thread; // a thread 19 20 // Override java.applet.Applet.init: 21 public void init () { 22 23 setBackground( Color.black ); 24 setForeground( Color.white ); 25 26 // Instantiate the polygon array: 27 polygon = new MovablePolygon[ numPoly ]; 28 29 // Instantiate a square: 30 polygon[0] = new Square( 75, 75, 70 ); 31 polygon[0].setDelta( 2, 3 ); 32 polygon[0].setColor( Color.red ); 33 34 // Instantiate a regular hexagon: 35 polygon[1] = new MovablePolygon( 125, 60, 50, 6 ); 36 polygon[1].setDelta( -3, 2 ); 37 polygon[1].setColor( Color.blue ); 38 39 // Instantiate an equilateral triangle: 40 polygon[2] = new MovablePolygon( 60, 125, 50, 3 ); 41 polygon[2].setDelta( -2, 2 ); 42 polygon[2].setColor( Color.green ); 43 44 } 45 46 // Override java.applet.Applet.start: 47 public void start() { 48 if ( thread == null ) { 49 thread = new Thread( this ); 50 thread.start(); 51 } 52 } 53 54 // Override java.applet.Applet.stop: 55 public void stop() { 56 if ( thread != null ) { 57 thread.stop(); 58 thread = null; 59 } 60 } 61 62 // Implement java.lang.Runnable.run: 63 public void run() { 64 while ( thread != null ) { 65 try { 66 Thread.sleep( 20 ); 67 } catch ( InterruptedException e ) { 68 // do nothing 69 } 70 repaint(); 71 } 72 } 73 74 // Override java.awt.Component.paint: 75 public void paint( Graphics g ) { 76 77 // Check, move, and fill each polygon: 78 for ( int i = 0; i < numPoly; i++ ) { 79 polygon[i].checkBounds( this.getBounds() ); 80 polygon[i].move(); 81 polygon[i].fill( g ); 82 } 83 84 } 85 86 }