/* * File: mObjApplet.java * * Double-buffered version of mRectApplet.java * with boundary checking */ import java.applet.*; import java.awt.*; public class mObjApplet extends Applet implements Runnable { // Instance variables: private int numObj = 3; // number of movable objects private mPoint object[]; // array of movable objects 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 object array: object = new mPoint[ numObj ]; // Instantiate a rectangle: object[0] = new mRectangle( 10, 10, 100, 100 ); object[0].setDelta( 2, 3 ); object[0].setColor( Color.red ); // Instantiate a circle: object[1] = new mOval( 200, 10, 100, 100 ); object[1].setDelta( -3, 2 ); object[1].setColor( Color.blue ); // Instantiate a triangle: object[2] = new mTriangle( 10, 200, 100, 100 ); object[2].setDelta( -2, 2 ); object[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() { thread = null; } // Implement java.lang.Runnable.run: public void run() { while ( thread != null ) { repaint(); try { Thread.sleep(20); } catch ( InterruptedException e ) { }; // Do nothing } } // Override java.awt.Component.update public void update (Graphics g) { paint (g); } // Override java.awt.Component.paint public void paint( Graphics g ) { // Fill background: gOffScreen.setColor( getBackground() ); gOffScreen.fillRect( 1, 1, getSize().width - 2, getSize().height - 2 ); // move each object after checking the boundary: for ( int i = 0; i < numObj; i++ ) { object[i].checkBoundary( getBounds() ); object[i].move(); object[i].paint(gOffScreen); } // Draw the buffer in the applet window: g.drawImage( buffer, 0, 0, this ); } }