简体   繁体   English

JavaFx KeyEvent不会移动对象

[英]JavaFx KeyEvent won't move object

I am currently trying to just make a really simple game as an experiment of what can be done with JavaFX, and I have a little rectangle that represents a person. 我目前正在尝试制作一个非常简单的游戏,作为对JavaFX可以完成的实验,并且我有一个代表人的小矩形。 The rectangle is set in a pane, and I'm trying to figure out how best to make it so the arrow keys make him move 5 px over to the left. 矩形是在窗格中设置的,我正在尝试弄清楚如何最好地制作矩形,因此箭头键使他向左移动了5像素。 The code below is what I'm trying. 下面的代码是我正在尝试的。 If you know how to make this code work or have better code for it, I would be very grateful. 如果您知道如何使此代码正常工作或具有更好的代码,我将不胜感激。

scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent ke) {
            if(ke.equals(KeyCode.KP_LEFT)) {
                int xLoc = (int)avatar.getX();
                int newX = xLoc - 5;
                int yLoc = (int)avatar.getY();
                avatar.relocate(newX, yLoc);
            }
        }
    });

Thank you! 谢谢!

KeyEvent不是代码,您需要getCode()

if (ke.getCode().equals(KeyCode.KP_LEFT))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM