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