1

Instead of using Swing's event-based keyPressed(keyEvent e) method to detect which keys are pressed on my keyboard, I would like to do a Thread that checks which keys are pressed every x seconds (so not getting the keys through the keyPressed event triggered by the OS).

I know how to do the thread, but I don't find any method/interface (I'm currently using KeyListener) to get which keys are pressed.

Can you help me?

Thank you

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
GriffinBabe
  • 146
  • 1
  • 12
  • 1
    What UI toolkit are you using? Both Swing and SWT have methods with that signature. – Andy Thomas Apr 04 '17 at 18:35
  • 1
    Using a KeyListener is a lot more efficient than continuously “asking” if a key has been pressed not to forget the delay you are creating this way. So why exactly do you want it like this? – Sjoerd Dal Apr 04 '17 at 18:37
  • http://stackoverflow.com/questions/17538182/getting-keyboard-input this might help you – Nikita Ivanov Apr 04 '17 at 18:37
  • @NikitaIvanov - That question covers scanning input from lines entered into the console. It does not cover this question. – Andy Thomas Apr 04 '17 at 18:41
  • Why do you want that? Is there an advantage you hope to obtain? Asking without having thought of any. – Ole V.V. Apr 04 '17 at 19:07
  • I use swing. The adventage is that I make a event based game, and I need a better control on the player moovements. If I use the event listener my character will move like typed letters moove on your computer when you let a key pressed :) – GriffinBabe Apr 04 '17 at 19:16
  • I don’t think there’s a bulletproof way of detecting auto-repeating keys from the user pressing a key in rapid succession in Java. I would suggest that your best bet is to filter out key events with the identical key code coming rapidly after each other. Probably `KeyEvent.getWhen()` will give you the best estimate of how close in time the events were. – Ole V.V. Apr 04 '17 at 19:44
  • 1
    `need a better control on the player moovements.` - you listen for the initial keyPressed and then you start a Timer to schedule the animation. On a keyReleased you stop the TImer. For example check out `KeyboardAnimtion` example found in [Motion Using the Keyboard](https://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/) – camickr Apr 04 '17 at 20:09

0 Answers0