Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Swing / AWT / SWT and the fly likes KeyEvent Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "KeyEvent Problem" Watch "KeyEvent Problem" New topic

KeyEvent Problem

Steffen Schmitt

Joined: May 08, 2008
Posts: 14
Hi everybody,

im doing a simple animation and it's bound to display a series of images when the arrow keys on the NUM pad are pressed. There shouln't be any problem abou this, but arrarently I don't even get the KeyEvents I hoped to process with my KeyAdapter:

I'd appreciate any suggestion about what I'm doing wrong here.

Thanks in advance,


The man who sets out to carry a cat by its tail learns something that will always be useful and which never will grow dim or doubtful.
-- Mark Twain
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
from the apidocs for KeyEvent:

"For key pressed and key released events, the getKeyCode method returns the
event's keyCode. For key typed events, the getKeyCode method always returns

even if you change your code to keyPressed(), you'll probably still have
problems - it will be better for you to use keyBindings
Suraj Chandran
Ranch Hand

Joined: May 20, 2008
Posts: 53
Replace keyTyped by keyReleased().

to Michael dunn,

I think adding keybindings instead of keylisteners in the above case
won't make any difference as key listeners are notified before key bindings:
The flow is like this(for JComponents):
1) key listeners
2) processComponentKeyEvent(), if the componenet overrides it
3) processKeyBindings..finally

So I think, from a design point of view, the user should actuall override processComponentKeyEvent() instead, as the given key behaviour of the componnet is tightly bound to how the component should be...just a feeling actually


I guess there are couple of design issues in this classic software the GOD coded.
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
Key bindings provide a high-level, loosely-coupled way to program keyboard input; they should always be the first tool the Swing programmer reaches for. Overriding processComponentKeyEvent(), on the other hand, is very low-level and tightly-coupled, and should only be done as a last resort, in my opinion.
subject: KeyEvent Problem
It's not a secret anymore!