getID() tells you they type of event, basically which listener was used. KeyCode() gets you a raw Keyboard code e.g. "A". keyChar() gets you the cooked character e.g. "a".
I suggest downloading my little KeyPlay application. You can play with it, clicking the mouse and hitting keystrokes. A description of the events generated is dumped to the console. With it, you can quickly learn about the ordering of events, and the use of the fields.
Happily, keyPressed(KeyEvent e)
only sees id=KeyEvent.KEY_PRESSED
events, keyTyped only
sees id=KEY_TYPED events,
and keyReleased only sees
id=KEY_RELEASED events.
Usually somewhere in the component or panel’s constructor, you must
remember to register your component as an interested listener with
this.addKeyListener(this); Make sure you don’t
do it more than once or you will see multiple keyPressed events per keystroke.
Your handler can use KeyEvent.consume()
to mark the keystroke as fully handled. This will discourage default keystroke
handling code from being invoked as well. Keep in mind your component won’t
see any keystroke events unless it has focus. Keep in mind that not all
components generate KeyEvents.
They may generate ActionEvents
or ItemStateChangedEvents
instead. See the essay under events for more details. (To come, techniques to
control additional pre or post processing on a keystroke by the superclass.) See
my essay on keystroke
accelerators on how I think user-configurable, globally-configurable,
keystroke accelerators should be implemented.
![]() |
and suggestions to improve this page to Roedy Green : | ||
| Canadian Mind Products | |||
| mindprod.com IP:[65.110.21.43] | |||
| Your face IP:[38.103.63.16] | The information on this page is for non-military use only. | ||
| You are visitor number 19,974. | Military use includes use by defence contractors. | ||
| You can get a fresh copy of this page from: | or possibly from your local J: drive (Java virtual drive/Mindprod website mirror) | ||
| http://mindprod.com/jgloss/keylistener.html | J:\mindprod\jgloss\keylistener.html | ||