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


Question

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?

1
4
6/10/2014 12:47:12 PM

Accepted Answer

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()));
16
7/6/2017 2:24:17 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon