简体   繁体   English

如何在JavaFX应用程序中的任何位置检测SPACE KeyEvent?

[英]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. 我想检测一个KeyEvent无论我的JavaFX应用程序中哪个元素有焦点 - 特别是,我想检测SPACE键。 I tried to add a listener to the Scene that corresponds to my window: 我试图在与我的窗口对应的Scene中添加一个监听器:

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. 但是如果我有一个具有焦点的特定节点(如ListViewButton ),则不会被检测到。

How can I detect when the SPACE key is pressed regardless of whatever the user is doing in my app? 无论用户在我的应用程序中执行什么操作,如何检测何时按下SPACE键? I don't intend to interrupt whatever node is receiving the KeyEvent - I just want to know if it happens. 我不打算中断接收KeyEvent任何节点 - 我只是想知道它是否发生。 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 您可以通过向根节点添加事件过滤器来检测KeyEvent

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 如果向上面的示例添加ComboBox或ColorPicker,则可以看到此行为

Here is your code 这是你的代码

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

        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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