Game Development Community

Java: Key Listeners with multiple Swing Components

by Steven Fletcher · in Technical Issues · 01/04/2005 (7:25 pm) · 5 replies

I programmed a small Java puzzle game that uses Swing.

It works, but I would like to add some keyboard hot keys.

The problem is that whenever you click on one of the Swing components, it shifts the focus to that Component. So I would have to have a KeyListener for EVERY component in the game just to have some hot keys that should apply no matter component you're using. I would be storing the keys pressed in an array and then checking what keys were pressed whenever necessary.

There has to be some good way to do this.

#1
01/04/2005 (7:35 pm)
Do a key listener for the actual Frame that you created to put the components in. That way no matter what component inside of the Frame has focus you'll get the key events.
#2
01/05/2005 (6:52 am)
You can also have a SINGLE key listener and just ASSIGN it to every component, this would be trival by having a base component that all the instances derive from. you are over-thinking the problem, there is always a simple way to do just about everything, if not it might not be worth doing :-)
#3
01/05/2005 (6:00 pm)
I already tried adding the key listener to the frame, but it didn't seem to work. Maybe I screwed up and added it to the wrong Component or something.

I'll try again tomorrow morning.
#4
01/05/2005 (6:12 pm)
Key listening on the frame worked fine in java 1.3

Java 1.4 broke that for a lot of applications, but 1.4 broke that in some ways. It also added global keyboard focus management. A simple kludgey way is to just SET the same key listener on all child components of the Frame's content pane recursively. Kludgey but its a small bit of code and jarrod is right that you can just use the same single listener assigned to all child components.
#5
01/06/2005 (8:00 pm)
I tried adding it to the frame again, but it didn't work. Given what Paul said, now I know why.

I'll just write a special "addComponentWithKeyListener" method that adds the KeyListener to each Component. And, yes, there'll only be the one KeyListener.

Anyways, thanks for the help. I'll just have to file this in the "weird things I hate about Java even though Java is generally cool" folder.