Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Listening for keyPressed Event  RSS feed

 
Russ Russell
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote a program that moves a gun left and right across a JPanel in response to the user pressing the left and right arrow keys. The program also fires bullets at falling objects by pressing the spacebar.

If I am gliding right or left with the arrow keys and then press the spacebar to fire, the arrow key stops responding. My program will only respond to the arrow key OR the spacebar, but not both at the same time (as if one looses focus when I press the other).

How can I have the program respond to the arrow key and the spacebar simultaneously? I tried removing setFocusable(true) and it didn't help.

Here is my code:



Thank you in advance,
-Russ
 
Rob Camick
Ranch Hand
Posts: 2800
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe this is normal behavour. That is a KeyEvent will only be generated for the last key used.

One solution for this is to "start" a Timer when the keyPressed event is generated and then "stop" the Timer when a keyReleased event is generated.

Read the section from the Swing tutorial on How to Use Swing Timers for more information.
 
Campbell Ritchie
Marshal
Posts: 55687
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this thread would sit better on the Swing forum. Moving.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!