【发布时间】:2017-03-22 09:31:45
【问题描述】:
我正在使用 JavaFX 开发一个简单的 Pong 克隆,但我很难移动桨。我想为此使用KeyEventDispatcher,并在AnimationTimer 循环期间检查按键。
我的Main 班级:
public class Main extends Application {
private Player m_pUser;
@Override
public void start(Stage primaryStage) throws Exception{
Group root = new Group();
Scene scene = new Scene(root, 500, 300);
ObservableList list = root.getChildren();
KeyPressedChecker kpc = new KeyPressedChecker();
m_pUser = new Player(kpc);
list.add(m_pUser.getPaddleDrawable());
GamePlayLoop gameLoop = new GamePlayLoop(m_pUser);
gameLoop.start();
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我的GamePlayLoop 班级:
public class GamePlayLoop extends AnimationTimer {
Player m_pUser;
public GamePlayLoop(Player p) {
m_pUser = p;
}
public void handle(long now) {
m_pUser.update();
}
}
我的KeyPressedChecker 班级:
public class KeyPressedChecker implements KeyEventDispatcher {
private static boolean downPressed = false;
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (KeyPressedChecker.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_DOWN)
downPressed = true;
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_DOWN)
downPressed = false;
break;
}
return false;
}
}
public static boolean isDownPressed() {
synchronized (KeyPressedChecker.class) {
return downPressed;
}
}
}
我的Player 班级:
public class Player {
private Paddle m_paddle;
private KeyPressedChecker m_kpc;
public Player(KeyPressedChecker kpc) {
m_paddle = new Paddle();
}
public Rectangle getPaddleDrawable() {
return m_paddle.getDrawable();
}
public void update() {
if (m_kpc.isDownPressed())
m_paddle.moveDown();
m_paddle.update();
}
}
最后是我的Paddle 班级:
public class Paddle {
private Rectangle m_rect;
private double m_nPosY;
public Paddle() {
m_rect = new Rectangle(10, 60);
}
public void moveDown() {
m_nPosY += 5;
}
public Rectangle getDrawable() {
return m_rect;
}
public void update() {
m_rect.setTranslateY(m_nPosY);
}
}
我的问题是桨在场景中没有平移。事实上,dispatchKeyEvent 根本没有被调用。这是为什么呢?
【问题讨论】:
标签: java javafx timer keyboard-events