Source of BounceApplet4.java


  1: //BounceApplet4.java
  2: //Demonstrates a bouncing ball, with Start and Stop buttons.
  3: //Once again the Ball class inherits from Thread.

  5: import java.awt.*;
  6: import java.awt.event.*;
  7: import java.applet.Applet;


 10: public class BounceApplet4
 11: extends Applet
 12: implements ActionListener
 13: {
 14:     private Button start, stop;
 15:     private Ball4 ball;

 17:     public void init()
 18:     {
 19:         start = new Button("Start");
 20:         add(start);
 21:         start.addActionListener(this);
 22:         stop = new Button("Stop");
 23:         add(stop);
 24:         stop.addActionListener(this);
 25:    }

 27:     public void actionPerformed(ActionEvent event)
 28:     {
 29:         if (event.getSource() == start)
 30:         {
 31:             Graphics g = getGraphics();
 32:             ball = new Ball4(g);
 33:             ball.start();
 34:         }
 35:         if (event.getSource() == stop)
 36:             ball.freeze();
 37:     }
 38: }

 40: 
 41: class Ball4 extends Thread
 42: {
 43:     private Graphics g;

 45:     private boolean keepGoing;

 47:     // Set rectangle and ball sizes
 48:     private int x = 150, xChange = 7;
 49:     private int y = 90, yChange = 3;
 50:     private int diameter = 10;

 52:     // Set initial ball position
 53:     private int leftX = 100, rightX = 200;
 54:     private int topY  = 40, bottomY = 140;


 57:     public Ball4(Graphics graphics)
 58:     {
 59:         g = graphics;
 60:         keepGoing = true;
 61:     }


 64:     public void freeze()
 65:     {
 66:         keepGoing = false;
 67:     }


 70:     public void run()
 71:     {
 72:         g.setColor(Color.white);
 73:         g.fillRect(leftX, topY, rightX-leftX, bottomY-topY);
 74:         Color backgroundColor = g.getColor();
 75:         while (keepGoing)
 76:         {
 77:             g.setColor(backgroundColor);
 78:             g.fillOval(x, y, diameter, diameter);

 80:             if (x<=leftX || x>=rightX)  xChange = -xChange;
 81:             if (y<=topY  || y>=bottomY) yChange = -yChange;
 82:             x = x + xChange;
 83:             y = y + yChange;

 85:             g.setColor(Color.red);
 86:             g.fillOval(x, y, diameter, diameter);
 87:             try
 88:             {
 89:                 sleep(30);
 90:             }
 91:             catch (InterruptedException e)
 92:             {
 93:                 System.err.println("Exception: " + e.toString());
 94:             }
 95:         }
 96:     }
 97: }