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