Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX Key Pressed event for scene not executed if there is a focused component

Tags:

java

javafx

I have a code to execute some function when some key is pressed:

scene.setOnKeyPressed(event -> {
    if (event.getCode() == KeyCode.F1) {
        doSomething();
    }
});

And it works, but only if there is no focused components, like a Button or a TextField. I noticed it works if i press CTRL+F1, or ALT+F1, or SHIFT+F1, but only F1 just works if there is no focused component. Is there a way to avoid this?

-----UPDATE----- As @James_D said, i can do it using eventFilter instead of eventHandler:

scene.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
    if (event.getCode().equals(KeyCode.ESCAPE)) {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(TelaPrincipalController.class.getResource("/br/com/atualy/checkout/layout/telaoperacoescaixa.fxml"));
            Parent parent = fxmlLoader.load();
            Scene scene = new Scene(parent, 600,400);
            Stage stage = new Stage();
            stage.setScene(scene);
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.initOwner(this.stage);
            stage.showAndWait();
            System.out.println("----> THIS IS BEING PRINTED TWICE ! <----");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});

The line 12 in this code gets printed twice for every ESC key press. Which means that when i press esc, it opens the new window, and when i close it, the window opens one more time. Can i solve it?

like image 484
Mateus Viccari Avatar asked Jun 09 '14 17:06

Mateus Viccari


1 Answers

Use an event filter instead. Some controls consume key press events, so using an event filter allows you to handle them before the control consumes them.

scene.addEventFilter(KeyEvent.KEY_PRESSED,
                event -> System.out.println("Pressed: " + event.getCode()));
like image 146
James_D Avatar answered Oct 16 '22 14:10

James_D