I have a JavaFx application whose main window has several buttons, I have assigned actions to the keys ENTER
and ESCAPE
with a code like this:
scene.setOnKeyReleased((KeyEvent keyEvent) -> {
System.out.println(" -> " + keyEvent.getCode().toString( )); // trace
if(keyEvent.getCode() == ENTER) {
// some action here
}
if(keyEvent.getCode() == ESCAPE) {
// some action here
}
});
The necessary imports are:
import javafx.scene.input.KeyEvent;
import static javafx.scene.input.KeyCode.ENTER;
import static javafx.scene.input.KeyCode.ESCAPE;
I have observed (in Windows) that if you press the "space bar" you press the keys of the program in succession, I would like to avoid this, that is to say leave the space key pressed without effect .
Note: In the example code I added a line to trace the key pressed, however pressing the space bar is not captured.
Edited: SOLUTION
Based on the response of Gorjesys that allows me to detect the key (space bar). The event is marked as consumed to avoid the behavior implemented by default. So the previous code would be:
// importaciones
import javafx.scene.input.KeyEvent;
import static javafx.scene.input.KeyCode.ENTER;
import static javafx.scene.input.KeyCode.ESCAPE;
import static javafx.scene.input.KeyCode.SPACE;
// ...
scene.setOnKeyReleased((KeyEvent keyEvent) -> {
System.out.println(" -> " + keyEvent.getCode().toString( )); // trace
if(keyEvent.getCode() == ENTER) {
// some action here
}
});
scene.addEventFilter(KeyEvent.KEY_PRESSED, (KeyEvent keyEvent) -> {
if (keyEvent.getCode() == ESCAPE) {
// some action here
}
if (keyEvent.getCode() == SPACE) {
keyEvent.consume();
// NOTE: Marks this Event as consumed to avoid the
// default behaviour
}
});
Note: I have moved the detection of the ESCAPE key because sometimes it is not detected by the method I used ( see question ).