Source of BouncingBall.java


  1: /* 
  2:  * Copyright (c) 1999-2002, Xiaoping Jia.  
  3:  * All Rights Reserved. 
  4:  */
  5: 
  6: import java.awt.*;
  7: 
  8: /**
  9:  *  The Bouncing Ball Applet
 10:  */
 11: public class BouncingBall
 12:     extends java.applet.Applet implements Runnable {
 13: 
 14:   protected Color color = Color.green;
 15:   protected int radius = 20;
 16:   protected int x, y;
 17:   protected int dx = -2, dy = -4;
 18:   protected Image image;
 19:   protected Graphics offscreen;
 20:   protected Dimension d;
 21: 
 22:   public void init() {
 23:     String att = getParameter("delay");
 24:     if (att != null) {
 25:       delay = Integer.parseInt(att);
 26:     }
 27:     d = getSize();
 28:     x = d.width * 2 / 3;
 29:     y = d.height - radius;
 30:   }
 31: 
 32:   public void update(Graphics g) {
 33:     // create the off-screen image buffer
 34:     // if it is invoked the first time
 35:     if (image == null) {
 36:       image = createImage(d.width, d.height);
 37:       offscreen = image.getGraphics();
 38:     }
 39: 
 40:     // draw the background
 41:     offscreen.setColor(Color.white);
 42:     offscreen.fillRect(0,0,d.width,d.height);
 43: 
 44:     // adjust the position of the ball
 45:     // reverse the direction if it touches
 46:     // any of the four sides
 47:     if (x < radius || x > d.width - radius) {
 48:       dx  =  -dx;
 49:     }
 50:     if (y < radius || y > d.height - radius) {
 51:       dy  =  -dy;
 52:     }
 53:     x += dx;
 54:     y += dy;
 55: 
 56:     // draw the ball
 57:     offscreen.setColor(color);
 58:     offscreen.fillOval(x - radius, y - radius,
 59:                        radius * 2, radius * 2);
 60: 
 61:     // copy the off-screen image to the screen
 62:     g.drawImage(image, 0, 0, this);
 63:   }
 64: 
 65:   public void paint(Graphics g) {
 66:     update(g);
 67:   }
 68: 
 69:   // The animation applet idiom
 70:   protected Thread bouncingThread;
 71:   protected int delay = 100;
 72: 
 73:   public void start() {
 74:     bouncingThread = new Thread(this);
 75:     bouncingThread.start();
 76:   }
 77: 
 78:   public void stop() {
 79:     bouncingThread = null;
 80:   }
 81: 
 82:   public void run() {
 83:     while (Thread.currentThread() == bouncingThread) {
 84:       try {
 85:         Thread.currentThread().sleep(delay);
 86:       } catch (InterruptedException  e) {}
 87:       repaint();
 88:     }
 89:   }
 90: 
 91: }