简体   繁体   中英

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.

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

Here is your code

        scene.setOnKeyReleased(event ->{
        if(event.getCode()== KeyCode.SPACE)
        {
            System.out.println("goog luck");
        }

        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM