Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaFX 8 Scene, Read Keyboard Input while running

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.

like image 994
JCoder Avatar asked Nov 01 '25 18:11

JCoder


1 Answers

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");
      }
});
like image 185
ItachiUchiha Avatar answered Nov 04 '25 10:11

ItachiUchiha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!