我编的是弹来弹去的小球,用了acm库,用**.move(dx,dy)来移动这个小球,当它碰到边界时改变dx,dy的正负弹来弹去,但是编译成功以后这个小球不弹来弹去。。。只是往窗口的右下角走,然后就消失了。。。求解释。。以下是源代码:
/*
* File: BouncingBall.java
* ---------------------------------------
* 这个程序让一个球运动并在弹到边框的时候又弹出去。
* */
import acm.program.*;
import acm.graphics.*;
public class BouncingBall extends GraphicsProgram {
public void run() {
int x = (getWidth() - BALL_SIZE) / 2;
int y = (getHeight() - BALL_SIZE) / 2;
int h = getHeight();
int w = getWidth();
GOval ball = new GOval(x , y , BALL_SIZE , BALL_SIZE);
add(ball);
int dx = XY;
int dy = XY;
while (true){
if ((y == h - BALL_SIZE) || y == 0) dy = -dy;
if ((x == w - BALL_SIZE) || x == 0) dx = -dx;
ball.move(dx , dy);
pause(PAUSE_TIME);
}
}
//Private constants
private static final int BALL_SIZE = 10;
private static final int PAUSE_TIME = 10;
private static final int XY = 1;
}
dy = -dy;
if ((x == w - BALL_SIZE) x == 0)
dx = -dx;
ball.move(dx, dy);
pause(PAUSE_TIME);
}
}
// Private constants
private static final int BALL_SIZE = 10;
private static final int PAUSE_TIME = 10;
private static final int XY = 1;
}
OK,程序调试结束,你可以运行下面的代码。
package TestLogin_claP;
/*
* File: BouncingBall.java
* ---------------------------------------
* 这个程序让一个球运动并在弹到边框的时候又弹出去。
* */
import acm.program.*;
import acm.graphics.*;
public class BouncingBall extends GraphicsProgram {
public void run() {
double x = (getWidth() - BALL_SIZE) / 2; // 用int不精确,运动不平滑
double y = (getHeight() - BALL_SIZE) / 2;
int h = getHeight();
int w = getWidth();
GOval ball = new GOval(x, y, BALL_SIZE, BALL_SIZE);
add(ball);
int dx = XY;
int dy = XY;
while (true) {
x = ball.getLocation().getX(); // 这两行你认真体会一下
y = ball.getLocation().getY(); //
h = getHeight();
w = getWidth();
if ((y == h - BALL_SIZE)