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 the "space bar" is pressed, the keys of the program are successively pressed, I would like to avoid this, that is, leave the pressing of the space key without effect .
Note: In the example code I added a line to trace the key pressed, however the space bar key press is not captured.
Edit: SOLUTION
Building on Gorjesys answer which 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 was using ( see question ).
In this case to detect the space bar you must use an Event Filter
In case you need to consume this event, simply use the InputEvent.consume() method :