/* * File: MovingPolygons2.java * * Moving polygons with boundary checking and double buffering * * Copyright: Northeast Parallel Architectures Center * */ import java.applet.Applet; import java.awt.*; public class MovingPolygons2 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 private Image buffer; // image object for double buffering private Graphics gOffScreen; // graphics object for double buffering // 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 ); // Create an off-screen image for double buffering: buffer = createImage( getSize().width, getSize().height ); // Get off-screen graphics context: gOffScreen = buffer.getGraphics(); } // 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.update: public void update( Graphics g ) { // Clear the buffer: gOffScreen.setColor( getBackground() ); gOffScreen.fillRect( 0, 0, getSize().width, getSize().height ); // Paint the polygons off screen, that is, in the buffer: paint( gOffScreen ); // Draw the buffer in the applet window: g.drawImage( buffer, 0, 0, this ); } // 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 ); } } }