The idea of my program is to create a picture and have that picture move up in a graphical window, which is exactly what the rollBall()
method does. The method works when I put the rollBall()
method in the run()
method. But the issue lies it cannot run when I put the rollBall()
method inside the keyPressed()
method.
I am using the acm.jar
library as it is a useful tool for creating java graphical program much easier.
Could someone please point me in the right direction.
This is my code...
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;
}