KeyListener : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

KeyListener

If you want your component to process its own keystrokes, the easiest way is for your component to implement the KeyListener interface. This means you must write three routines, that the system calls each time the user hits a key. You always get a KeyEvent.KEY_PRESSED and KEY_RELEASED event, even for keys like Shift, Alt and function keys. You won’t get a KEY_TYPED event when the user hits a key like Shift, Alt or a function key, but it may alter the effect of some other key that does generate a KEY_TYPED event.

// methods of a KeyListener interface
public void keyPressed( KeyEvent e )

public void keyTyped( KeyEvent e )

public void keyReleased( KeyEvent e )

The various combinations of ID, keyCode() and keyChar() in the keyEvent are quite complicated.

getID() tells you the 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.

Learning More

Oracle’s Javadoc on KeyListener interface : available:
Java version 1.1 or later events
keystroke events
Robot: to generate simulated keystrokes

This page is posted
on the web at:

http://mindprod.com/jgloss/keylistener.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\keylistener.html
Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[18.218.61.16]
You are visitor number