同时按下JavaFX检测多个键盘键 [英] JavaFX Detect mutliple keyboard keys pressed simultaneously
问题描述
正如标题所说,我想检测同时按下多个键盘键(同时)并按下(同时)一段时间。我试图在 Scene
上添加多个事件处理程序,但它不起作用:
As the title is saying I want to detect multiple keyboard keys pressed at the same time (simultaneously) and are being pressed (simultaneously) for a time period. I am trying to add multiple event handlers on the Scene
but it doesn't work:
EventHandler<KeyEvent> handler1 = key -> {
//logic1 here
}
EventHandler<KeyEvent> handler2 = key -> {
//logic1 here
}
getScene().addEventHandler(KeyEvent.KEY_PRESSED, handler1);
getScene().addEventHandler(KeyEvent.KEY_PRESSED, handler2);
为什么我要这样做:
我有一些代码,我想基于用户按下的键盘键
来调整矩形的大小。例如,如果用户按下右箭头
矩形从右侧增加,如果用户按向上箭头
,矩形从顶部开始增加支持
I have some code and I want to resize a rectangle based on the keyboard keys
pressed by the user.For example if the user is pressing RIGHT ARROW
the rectangle is increasing to from right side and if the user is pressing UP ARROW
the rectangle is increasing from the top side.
问题:
但是当用户按下[右箭头
]和[向上箭头
]同时按住它们,上面的两个动作必须一起发生,而不仅仅是其中一个。
But when the user is pressing [RIGHT ARROW
] and [UP ARROW
] simultaneously and keeping them pressed,the two actions above must happen together,and not only one of them.
推荐答案
只需操作一些布尔属性:
Just manipulate some boolean properties:
private BooleanProperty upPressed = new SimpleBooleanProperty();
private BooleanProperty rightPressed = new SimpleBooleanProperty();
private BooleanBinding anyPressed = upPressed.or(rightPressed);
// ...
getScene().setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP) {
upPressed.set(true);
}
if (e.getCode() == KeyCode.RIGHT) {
rightPressed.set(true);
}
});
getScene().setOnKeyReleased(e -> {
if (e.getCode() == KeyCode.UP) {
upPressed.set(false);
}
if (e.getCode() == KeyCode.RIGHT) {
rightPressed.set(false);
}
});
如果同时按下两个键,则两个属性都为true,因此您可以使用布尔值注册侦听器属性,或根据需要在 AnimationTimer
中检查它们,例如:
If both keys are pressed simultaneously, both properties will be true, so you can register listeners with the boolean properties, or check them in an AnimationTimer
as you need, e.g.:
double delta = .. ;
AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long timestamp) {
if (upPressed.get()) {
rect.setY(rect.getY()-delta);
rect.setHeight(rect.getHeight() + delta);
}
if (rightPressed.get()) {
rect.setWidth(rect.getWidth() + delta);
}
}
};
anyPressed.addListener((obs, wasPressed, isNowPressed) -> {
if (isNowPressed) {
timer.start();
} else {
timer.stop();
}
});
这篇关于同时按下JavaFX检测多个键盘键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!