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
How do I run a function on a specific key press in JavaFX?
提问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");
}
});