java 使用 JavaFX 8 场景,在运行时读取键盘输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29179036/
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 14:49:18  来源:igfitidea点击:

Using JavaFX 8 Scene, Read Keyboard Input while running

javajavafxkeyeventkeycodescene

提问by JCoder

I have my JavaFX 8 Scene going nicely. Now, while everything else is happening, I would like to continuously check for any KeyEvent/KeyCode while the program is running. I have a Timeline called timeline set to INDEFINITE and I've set my cycle count to indefinite with

我的 JavaFX 8 场景运行良好。现在,当其他一切都在发生时,我想在程序运行时不断检查任何 KeyEvent/KeyCode。我有一个名为时间轴的时间线设置为 INDEFINITE 并且我已将我的周期计数设置为无限期

timeline.setCycleCount(Timeline.INDEFINITE);

I'm looking for an easy method that is also clean and won't make my program choppy.

我正在寻找一种简单的方法,它也很干净并且不会使我的程序断断续续。

回答by ItachiUchiha

You can use a KeyEventlistener to listen to when key is pressed, release, typedor anyof them. It does matter whether you have some infinite loop running on another thread, if the user presses a button, the listener will be called.

您可以使用KeyEvent侦听器来侦听 key 被按下释放键入或其中任何一个的时间。您是否在另一个线程上运行一些无限循环很重要,如果用户按下按钮,则将调用侦听器。

You just need to add a listenerto the scene and the key event which you want to listen to.

您只需要在场景中添加一个监听器和您想要监听的关键事件。

scene.addEventHandler(KeyEvent.KEY_PRESSED, (key) -> {
      if(key.getCode()==KeyCode.ENTER) {
          System.out.println("You pressed enter");
      }
});