Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect the SPACE KeyEvent anywhere in my JavaFX app?

I want to detect a KeyEvent regardless of what element has focus in my JavaFX app - in particular, I want to detect the SPACE key. I tried to add a listener to the Scene that corresponds to my window:

scene.setOnKeyPressed(ev -> {
    if (ev.getCode() == KeyCode.SPACE) {
        System.out.println("GOOD");
    }
});

But if I have a particular node with focus (like a ListView or Button) then it won't be detected.

How can I detect when the SPACE key is pressed regardless of whatever the user is doing in my app? I don't intend to interrupt whatever node is receiving the KeyEvent - I just want to know if it happens. One (ugly) solution would be adding the listener to all my nodes, but I would rather not if possible.

like image 843
Voldemort Avatar asked Oct 30 '22 02:10

Voldemort


1 Answers

You can detect the KeyEvent by adding an event filter to the root node

Here is a quick example using some of the controls you mentioned:

@Override
    public void start(Stage primaryStage) throws Exception{
        TextField textfield = new TextField();
        ListView listView = new ListView();
        listView.getItems().add("One");
        listView.getItems().add("Two");
        listView.getItems().add("Three");
        Button button = new Button("Button");

        VBox root = new VBox(5, textfield, listView, button);
        root.addEventFilter(KeyEvent.KEY_PRESSED, event->{
            if (event.getCode() == KeyCode.SPACE) {
                System.out.println("GOOD");
            }
        });
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(10));
        primaryStage.setScene(new Scene(root, 400, 400));
        primaryStage.show();
    }

Note: On controls that generate a popup / overlay, a space might not be detected while it is showing, but will be detected when hidden yet still in focus. You can see this behaviour if you add a ComboBox or ColorPicker to the above example

like image 150
Peter Avatar answered Nov 14 '22 01:11

Peter