[英]JavaFX Detect mutliple keyboard keys pressed simultaneously
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: 我试图在Scene
上添加多个事件处理程序,但它不起作用:
EventHandler<KeyEvent> handler1 = key -> {
//logic1 here
}
EventHandler<KeyEvent> handler2 = key -> {
//logic1 here
}
getScene().addEventHandler(KeyEvent.KEY_PRESSED, handler1);
getScene().addEventHandler(KeyEvent.KEY_PRESSED, handler2);
Why I want to do this: 为什么我要这样做:
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. 我有一些代码,我想基于用户按下的keyboard keys
来调整矩形的大小。例如,如果用户按下RIGHT ARROW
,矩形从右侧增加,如果用户按下UP ARROW
,矩形正在增加从顶端。
The problem: 问题:
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. 但是当用户同时按下[ RIGHT ARROW
]和[ UP ARROW
]并按住它们时,上面的两个动作必须一起发生,而不仅仅是其中一个动作。
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);
}
});
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, eg: 如果同时按下两个键,则两个属性都为true,因此您可以使用布尔属性注册侦听器,或者根据需要在AnimationTimer
检查它们,例如:
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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.