wood burning stoves 2.0
The moose likes Swing / AWT / SWT and the fly likes Listening for keyPressed Event Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Listening for keyPressed Event" Watch "Listening for keyPressed Event" New topic

Listening for keyPressed Event

Russ Russell
Ranch Hand

Joined: Jan 24, 2010
Posts: 72
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,
Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2452
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

Joined: Oct 13, 2005
Posts: 46375
I think this thread would sit better on the Swing forum. Moving.
I agree. Here's the link: http://aspose.com/file-tools
subject: Listening for keyPressed Event
It's not a secret anymore!