Source of BounceApplet1.java


  1: //BounceApplet1.java
  2: //Attempts to demonstrate a bouncing ball.
  3: //But, there appears to be a major problem.
  4: //What is it?  And how do we remedy it?

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


 10: public class BounceApplet1 extends Applet
 11: {
 12:     //Set rectangle and ball sizes
 13:     private int x = 60, xChange = 7;
 14:     private int y = 60, yChange = 3;
 15:     private int diameter = 10;

 17:     //Set initial ball position
 18:     private int leftX = 10, rightX  = 110;
 19:     private int topY  = 10, bottomY = 110;


 22:     public void paint(Graphics g)
 23:     {
 24:         g.drawRect(leftX, topY, rightX-leftX, bottomY-topY);
 25:         for (int n=1; n<1000; n++)
 26:         {
 27:             Color backgroundColour = getBackground();
 28:             g.setColor(backgroundColour);
 29:             g.fillOval(x, y, diameter, diameter);

 31:             if (x<=leftX+5 || x>=rightX-12)  xChange = -xChange;
 32:             if (y<=topY+5  || y>=bottomY-12) yChange = -yChange;
 33:             x = x + xChange;
 34:             y = y + yChange;

 36:             g.setColor(Color.red);
 37:             g.fillOval(x, y, diameter, diameter);
 38:         }
 39:     }
 40: }