Cancel key events in JavaFx

3

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 ).

    
asked by Orici 15.09.2018 в 01:30
source

1 answer

0

In this case to detect the spacebar you should use a Event Filter

import static javafx.scene.input.KeyCode.SPACE;
...
...

    scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
            public void handle(KeyEvent keyEvent) {

                           if (keyEvent.getCode() == SPACE) {
                              System.out.println("Tecla SPACE!");
                            }

            }
        });

In case you need to consume this event simply use the method InputEvent.consume () :

                       if (keyEvent.getCode() == SPACE) {
                          System.out.println("Tecla SPACE!");

                              keyEvent.consume();


                        }
    
answered by 15.09.2018 / 01:54
source