This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Listening for keyPressed Event

 
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: 2534
9
  • 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
Sheriff
Posts: 48363
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this thread would sit better on the Swing forum. Moving.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic