Using JavaFX 8 Scene, Read Keyboard Input while running

17,272

You can use a KeyEvent listener to listen to when key is pressed, release, typed or any of them. It doesn't matter what you have running on other threads, whether that's some infinite loop, or anything else; if the user presses a button, the listener will be called.

You just need to add a listener to 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");
      }
});
Share:
17,272

Related videos on Youtube

JCoder
Author by

JCoder

Gamer. What I use most: Java, C++, C#, JavaScript.

Updated on June 04, 2022

Comments

  • JCoder
    JCoder almost 2 years

    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

    timeline.setCycleCount(Timeline.INDEFINITE);
    

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

    • ItachiUchiha
      ItachiUchiha about 9 years
      Why do you need a TimeLine for listening to KeyEvents?
    • JCoder
      JCoder about 9 years
      I'm doing animations, that's all I have so far. I now want to be able to do stuff like, restart the animation, or display a button on the screen, or anything else, based on user input from keys. I only mentioned it because I was worried about interruptions.
  • JCoder
    JCoder about 9 years
    Thank you, ItachiUchiha!
  • Pieter De Bie
    Pieter De Bie about 8 years
    I guess you mean "it doesn't matter"?