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