我的程序的想法是创建一张图片并让该图片在图形窗口中向上移动,这正是该rollBall()
方法所做的。当我将方法放入rollBall()
方法中时,该run()
方法有效。rollBall()
但问题在于当我将方法放入方法中时它无法运行keyPressed()
。
我正在使用该acm.jar
库,因为它是一个有用的工具,可以更轻松地创建 java 图形程序。
有人可以指出我正确的方向。
这是我的代码...
import java.awt.Color;
import java.awt.event.KeyEvent;
import acm.graphics.GImage;
import acm.graphics.GOval;
import acm.program.GraphicsProgram;
import acm.util.RandomGenerator;
public class BallDrop extends GraphicsProgram {
/** width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 900;
public static final int APPLICATION_HEIGHT = 768;
private static final double GRAVITY = 1;
/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 50;
private static final int WIDTH = APPLICATION_WIDTH;
public void run() {
setSize(APPLICATION_WIDTH, APPLICATION_HEIGHT);
addKeyListeners();
}
public void keyPressed(KeyEvent e){
char linkMoveRightKey = e.getKeyChar();
if(linkMoveRightKey == 'z'){
rollBall();
}
}
private void rollBall(){
setup_Ball();
game_Loop();
}
private void setup_Ball(){
pic = new GImage("link.png");
add(pic,gameBallInitialLocationX, gameBallInitialLocationY);
}
private void game_Loop(){
while(pic.getX() > 0 ){
move_Ball();
pause(DELAY);
}
}
private void move_Ball() {
ballVelocityX = 0;
ballVelocityY -= GRAVITY;
pic.move(ballVelocityX, ballVelocityY);
}
private RandomGenerator rgen = RandomGenerator.getInstance();
private GImage pic;
private int gameBallInitialLocationX = 500;
private int gameBallInitialLocationY = 500;
private int ballVelocityX = (int) rgen.nextDouble(3.0, 5.0);
private int ballVelocityY =10;
private static final int DELAY = 50;
}