How are multiple key events detected in a single scene? I need my program to detect when the space bar and the right arrow keys are pressed simultaneously.
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
if (ke.getCode() == KeyCode.RIGHT) {
///
}
if (ke.getCode() == KeyCode.LEFT) {
///
}
if (ke.getCode() == KeyCode.SPACE) {
///
}
if (ke.getCode() == KeyCode.RIGHT && ke.getCode() == KeyCode.SPACE) {
// How??
}
}
});
The first 3 expressions look for a single key and work fine. The final expression never returns true. I believe only the latest key event is passed to the handler.
I looked at KeyCodeCombination, however this appears to be for use in cases when a key has a modifier key from a specified list (ALT_DOWN, SHIFT_DOWN, etc).
Is there a utility in FX that I can use?
Try this:
final BooleanProperty spacePressed = new SimpleBooleanProperty(false);
final BooleanProperty rightPressed = new SimpleBooleanProperty(false);
final BooleanBinding spaceAndRightPressed = spacePressed.and(rightPressed);
// How to respond to both keys pressed together:
spaceAndRightPressed.addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<Boolean> obs, Boolean werePressed, Boolean arePressed) {
System.out.println("Space and right pressed together");
}
});
// Wire up properties to key events:
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent ke) {
if (ke.getCode() == KeyCode.SPACE) {
spacePressed.set(true);
} else if (ke.getCode() == KeyCode.RIGHT) {
rightPressed.set(true);
}
}
});
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent ke) {
if (ke.getCode() == KeyCode.SPACE) {
spacePressed.set(false);
} else if (ke.getCode() == KeyCode.RIGHT) {
rightPressed.set(false);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With