wood burning stoves*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Listening for keyPressed Event" Watch "Listening for keyPressed Event" New topic
Author

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,
-Russ
Rob Camick
Ranch Hand

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

Joined: Oct 13, 2005
Posts: 37907
    
  22
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
 
Similar Threads
KeyListener
Help with GlassPane intercepting Key events
setFocus in JButton is there any?
Java KeyListener - can't detect multiple pressed buttons
simple KeyEvent to move graphic