I have two JPanels. In the first one I have 3 JButtons and the second one is to draw images based on events read from the keyboard. If I set the JButtons with setEnabled(false);
I can use the keyboard events as I expect (If I press up arrow the image moves up), but when the buttons are enabled nothing happens with the image. Even, if I press the space bar it behaves like if I clicked the button.
Asked
Active
Viewed 526 times
1

Hovercraft Full Of Eels
- 283,665
- 25
- 256
- 373

Ángel Araya
- 225
- 1
- 8
1 Answers
5
The problem is not with the JButtons, but is likely because your using a KeyListener. Don't use KeyListeners with Swing GUI's if you can avoid it and instead use Key Bindings. KeyListeners only work if the component being listened to has the focus, and when you have JButtons present, they will take the focus and prevent your KeyListener from working. Key Bindings, if done right, can avoid this problem.
For example, please see my code example here.

Community
- 1
- 1

Hovercraft Full Of Eels
- 283,665
- 25
- 256
- 373
-
Using key bindings solved the problem. Thanks. But now I found myself looking for the name of each key I need. – Ángel Araya Aug 14 '12 at 04:55