/* * File: MovingPolygons.java * * Moving polygons with boundary checking * * Copyright: Northeast Parallel Architectures Center * */ import java.applet.Applet; import java.awt.*; public class MovingPolygons extends Applet implements Runnable { // Instance variables: private final int numPoly = 3; // number of drawable polygons private MovablePolygon polygon[]; // array of drawable polygons private Thread thread; // a thread // Override java.applet.Applet.init: public void init () { setBackground( Color.black ); setForeground( Color.white ); // Instantiate the polygon array: polygon = new MovablePolygon[ numPoly ]; // Instantiate a square: polygon[0] = new Square( 75, 75, 70 ); polygon[0].setDelta( 2, 3 ); polygon[0].setColor( Color.red ); // Instantiate a regular hexagon: polygon[1] = new MovablePolygon( 125, 60, 50, 6 ); polygon[1].setDelta( -3, 2 ); polygon[1].setColor( Color.blue ); // Instantiate an equilateral triangle: polygon[2] = new MovablePolygon( 60, 125, 50, 3 ); polygon[2].setDelta( -2, 2 ); polygon[2].setColor( Color.green ); } // Override java.applet.Applet.start: public void start() { if ( thread == null ) { thread = new Thread( this ); thread.start(); } } // Override java.applet.Applet.stop: public void stop() { if ( thread != null ) { thread.stop(); thread = null; } } // Implement java.lang.Runnable.run: public void run() { while ( thread != null ) { try { Thread.sleep( 20 ); } catch ( InterruptedException e ) { // do nothing } repaint(); } } // Override java.awt.Component.paint: public void paint( Graphics g ) { // Check, move, and fill each polygon: for ( int i = 0; i < numPoly; i++ ) { polygon[i].checkBounds( this.getBounds() ); polygon[i].move(); polygon[i].fill( g ); } } }