画一个不停反弹的小球。
1 /* 2 * File:BouncingBall.java 3 * ------------------- 4 * This program draw a bouncing ball. 5 */ 6 7 import acm.program.*; 8 import acm.graphics.*; 9 import java.awt.*; 10 11 public class BouncingBall extends GraphicsProgram { 12 13 public void run(){ 14 int x = (getWidth() - DIAMETER) / 2; 15 int y = (getHeight() - DIAMETER) / 2; 16 GOval ball = new GOval(x, y,DIAMETER, DIAMETER); 17 ball.setFilled(true); 18 add(ball); 19 int dx = 1; 20 int dy = 1; 21 while(true){ 22 ball.move(dx, dy); 23 pause(PAUSE_TIME); 24 x += dx; 25 y += dy; 26 if(x > getWidth() - DIAMETER || x < 0) dx = -dx; 27 if(y > getHeight() - DIAMETER || y < 0) dy = -dy; 28 } 29 } 30 /* Private constants */ 31 private static final int DIAMETER = 40; 32 private static final int PAUSE_TIME = 20; 33 34 }