//********************************************************************* // Ball.java Author: Professor M. Liu // // An applet which displays a bouncing ball. // //********************************************************************** import java.awt.*; import java.applet.Applet; public class Ball extends Applet { // rectangle upper left corner position final int XSTART = 200; final int YSTART = 10; // rectangle size final int SIZE = 300; // ball position and size private int x = XSTART + 7, xChange = 7; private int y = YSTART + 2, yChange = 2; private int DIAMETER=10; private int rectLeftX = XSTART, rectRightX = XSTART + SIZE; private int rectTopY = YSTART, rectBottomY = YSTART + SIZE; public void paint (Graphics g) { g.drawRect(rectLeftX, rectTopY, rectRightX-rectLeftX, rectBottomY-rectTopY); // how many times do you want the ball to move? final int NUM_TIMES = 500; for (int n = 1; n< NUM_TIMES; n++) { Color backgroundColor = getBackground(); g.setColor(backgroundColor); g.fillOval (x, y, DIAMETER, DIAMETER); if (x + xChange <= rectLeftX) xChange = -xChange; if(x+xChange+DIAMETER >= rectRightX) xChange = -xChange; if (y+yChange <= rectTopY) yChange = -yChange; if(y+yChange+DIAMETER >= rectBottomY) yChange = -yChange; x = x + xChange; y = y + yChange; // This controls how fast the ball moves final int SPEED = 100; // Set ball color here g.setColor(Color.red); g.fillOval (x, y, DIAMETER, DIAMETER); try { Thread.sleep(SPEED); } catch (InterruptedException e) { g.drawString("sleep exception", 20, 20); } } } }