java 如何在 JavaFX 中的特定按键上运行函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33224161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:23:11  来源:igfitidea点击:

How do I run a function on a specific key press in JavaFX?

javajavafxkeyboardevent-handling

提问by user2560035

I have a program in javafx that is running and I want to call a function inside that program when a specific key is pressed on the keyboard (for example, the "a" key). I tried using an event handler on my scene but KEY_PRESSED seems to go off when any key is pressed, unless I am using it wrong. KEY_TYPED seems like it might suit my needs, but I've only found examples of that one in relation to text boxes, which is not what I'm looking for. Does anyone know how to do this, or have a good resource I can consult for something like this

我在 javafx 中有一个正在运行的程序,当按下键盘上的特定键(例如,“a”键)时,我想调用该程序中的一个函数。我尝试在我的场景中使用事件处理程序,但 KEY_PRESSED 似乎在按下任何键时关闭,除非我使用错误。KEY_TYPED 似乎可能适合我的需求,但我只找到了与文本框相关的示例,这不是我要找的。有谁知道如何做到这一点,或者有一个很好的资源我可以咨询这样的事情

回答by James_D

Just check the code of the key that was pressed:

只需检查按下的键的代码:

scene.setOnKeyPressed(e -> {
    if (e.getCode() == KeyCode.A) {
        System.out.println("A key was pressed");
    }
});

回答by Roland

Use an event filter and whatever keyeventyou need, here I use ANY:

使用事件过滤器和您需要的任何事件,这里我使用ANY

        scene.addEventFilter(KeyEvent.ANY, keyEvent -> {
            System.out.println(keyEvent);
        });