1 /* 2 * File: MovingPolygons2.java 3 * 4 * Moving polygons with boundary checking, a MovablePolygon class, 5 * and double buffering 6 * 7 * Copyright: Northeast Parallel Architectures Center 8 * 9 */ 10 11 import java.applet.Applet; 12 import java.awt.*; 13 14 public class MovingPolygons2 extends Applet implements Runnable { 15 16 // Instance variables: 17 private final int numPoly = 3; // number of movable polygons 18 private MovablePolygon polygon[]; // array of movable polygons 19 private Thread thread; // a thread 20 private Image buffer; // image object for double buffering 21 private Graphics gOffScreen; // graphics object for double buffering 22 23 // Override java.applet.Applet.init: 24 public void init () { 25 26 setBackground( Color.black ); 27 setForeground( Color.white ); 28 29 // Instantiate the polygon array: 30 polygon = new MovablePolygon[ numPoly ]; 31 32 // Instantiate a square: 33 polygon[0] = new MovablePolygon( 75, 75, 50, 4 ); 34 polygon[0].setDelta( 2, 3 ); 35 polygon[0].setColor( Color.red ); 36 37 // Instantiate a regular hexagon: 38 polygon[1] = new MovablePolygon( 125, 60, 50, 6 ); 39 polygon[1].setDelta( -3, 2 ); 40 polygon[1].setColor( Color.blue ); 41 42 // Instantiate an equilateral triangle: 43 polygon[2] = new MovablePolygon( 60, 125, 50, 3 ); 44 polygon[2].setDelta( -2, 2 ); 45 polygon[2].setColor( Color.green ); 46 47 // Create an off-screen image for double buffering: 48 buffer = createImage( getSize().width, getSize().height ); 49 // Get off-screen graphics context: 50 gOffScreen = buffer.getGraphics(); 51 52 } 53 54 // Override java.applet.Applet.start: 55 public void start() { 56 if ( thread == null ) { 57 thread = new Thread( this ); 58 thread.start(); 59 } 60 } 61 62 // Override java.applet.Applet.stop: 63 public void stop() { 64 if ( thread != null ) { 65 thread.stop(); 66 thread = null; 67 } 68 } 69 70 // Implement java.lang.Runnable.run: 71 public void run() { 72 while ( thread != null ) { 73 try { 74 Thread.sleep( 20 ); 75 } catch ( InterruptedException e ) { 76 // do nothing 77 } 78 repaint(); 79 } 80 } 81 82 // Override java.awt.Component.update: 83 public void update( Graphics g ) { 84 85 // Clear the buffer: 86 gOffScreen.setColor( getBackground() ); 87 gOffScreen.fillRect( 0, 0, getSize().width, getSize().height ); 88 89 // Paint the polygons off screen, that is, in the buffer: 90 paint( gOffScreen ); 91 92 // Draw the buffer in the applet window: 93 g.drawImage( buffer, 0, 0, this ); 94 95 } 96 97 // Override java.awt.Component.paint: 98 public void paint( Graphics g ) { 99 100 // Check, move, and fill each polygon: 101 for ( int i = 0; i < numPoly; i++ ) { 102 polygon[i].checkBounds( this.getBounds() ); 103 polygon[i].move(); 104 polygon[i].fill( g ); 105 } 106 107 } 108 109 }