JAVA   85

Bounce Applet 1

Guest on 10th July 2022 06:03:58 AM

  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?
  5.  
  6. import java.awt.*;
  7. import java.applet.Applet;
  8.  
  9.  
  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;
  16.  
  17.     //Set initial ball position
  18.     private int leftX = 10, rightX  = 110;
  19.     private int topY  = 10, bottomY = 110;
  20.  
  21.  
  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);
  30.  
  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;
  35.  
  36.             g.setColor(Color.red);
  37.             g.fillOval(x, y, diameter, diameter);
  38.         }
  39.     }
  40. }

Raw Paste


Login or Register to edit or fork this paste. It's free.