Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks

Writing a Key Listener

Key events tell you when the user types at the keyboard. Specifically, key events are generated by the component with the keyboard focus when the user presses or releases keyboard keys. (For information about focus, see the focus discussion in Writing a Focus Listener.)

You can be notified about two basic kinds of key events: the typing of a Unicode character, and the pressing or releasing of a key on the keyboard. The first kind of event is called a key typed event. The second kind are key pressed and key released events.

In general, you should try to use key typed events unless you need to know when the user presses keys that don't correspond to characters. For example, if you want to know when the user types some Unicode character -- even one that results from the user pressing several keys in sequence -- listen for key typed events. On the other hand, if you want to know when the user presses the F1 character, you need to listen for key pressed/released events.


Note: To generate keyboard events, a component must have the keyboard focus.

To make a component get the keyboard focus, follow these steps:

  1. Make sure the component that the user will be typing into can get the keyboard focus. For example, on some systems, labels might not be able to get the keyboard focus.
  2. Make sure that the component requests the focus when appropriate. For custom components, you'll probably need to implement a MouseListener that calls the requestFocus method when the component is clicked.
  3. If you're writing a custom component, implement the component's isFocusTraversable method so that it returns true. This lets the user tab to your component.

Key Event Methods

The KeyListener(in the API reference documentation) interface and its corresponding adapter class, KeyAdapter(in the API reference documentation), contain three methods:
void keyTyped(KeyEvent)
Called by the AWT just after the user types a Unicode character into the listened-to component.
void keyPressed(KeyEvent)
Called by the AWT just after the user presses a key on the keyboard.
void keyReleased(KeyEvent)
Called by the AWT just after the user releases a key on the keyboard.

Examples of Handling Key Events

The following applet demonstrates key events. It consists of a text field that you can type into, followed by a text area that displays a message every time the text field fires a key event. A button at the bottom of the applet lets you clear both the text field and text area.


Note: The above applet requires JDK 1.1. If you are using an older browser that does not support 1.1, you won't be able to run the applet. Instead, you need to view this page in a 1.1-compliant browser, such as HotJava or the JDK Applet Viewer (appletviewer).

Try this:
  1. Click in the applet's text field so that it gets the keyboard focus.
  2. Press and release the A key on the keyboard.
    The text field fires three events: a key pressed event, a key typed event, and a key released event. Note that the key typed event doesn't have key code information; they also don't have modifier information. If you care only about which characters the user types, you should handle key typed events. If you care about which keys the user presses/releases, you should handle key pressed/released events.
  3. Press the Clear button.
    You might want to do this after each of the following steps.
  4. Press and release the Shift key.
    The text field fires two events: a key pressed and a key released. The text field doesn't generate a key typed event because Shift, by itself, doesn't correspond to any character.
  5. Type an uppercase A by pressing the Shift and A keys.
    You'll see the following events, although perhaps not in this order: key press (Shift), key press (A), key typed ('A'), key release (A), key release (Shift).
  6. Type an uppercase A by pressing and releasing the Caps Lock key, and then pressing the A key.
    You should see the following events: key press (Caps Lock), key press (A), key typed ('A'), key release (A). Notice that the Caps Lock key doesn't generate a key release event until you press and release it again. The same is true of other state keys, such as Scroll Lock and Num Lock.
  7. Press and hold the A key.
    Does it automatically repeat? If so, you'll see the same events that you would have seen if you pressed and released the A key repeatedly.

You can find the applet's code in KeyEventDemo.java. Here is the applet's key event handling code:

public class KeyEventDemo ...  implements KeyListener ... {
    ...//where initialization occurs:
	typingArea = new TextField(20);
	typingArea.addKeyListener(this);
    ...
    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
	displayInfo(e, "KEY TYPED: ");
    }

    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
	displayInfo(e, "KEY PRESSED: ");
    }

    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {
	displayInfo(e, "KEY RELEASED: ");
    }
    ...
    protected void displayInfo(KeyEvent e, String s){
	...
	char c = e.getKeyChar();
	int keyCode = e.getKeyCode();
	int modifiers = e.getModifiers();
	...
	tmpString = KeyEvent.getKeyModifiersText(modifiers);

	...//display information about the KeyEvent...
    }
}

The KeyEvent Class

Each key event method has a single parameter: a KeyEvent(in the API reference documentation) object. The KeyEvent class defines the following useful methods:

int getKeyChar()
void setKeyChar(char)
Get or set the Unicode character associated with this event.

int getKeyCode()
void setKeyCode(int)
Get or set the key code associated with this event. The key code identifies the particular key on the keyboard that the user pressed or released. The KeyEvent class defines many key code constants for commonly seen keys. For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies the ESCAPE key.

void setModifiers(int)
Sets the state of the modifier keys for this event. Also see the InputEvent getModifiers method.
Other potentially useful methods in KeyEvent include methods that generate localizable text descriptions of key codes and modifier keys.

The KeyEvent class extends InputEvent(in the API reference documentation), which extends ComponentEvent(in the API reference documentation). ComponentEvent provides the handy getComponent method. InputEvent provides the following useful methods:

int getWhen()
Returns the timestamp of when this event occurred. The higher the timestamp, the more recently the event occurred. [CHECK!]

boolean isAltDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
Convenient methods giving you the state of the modifier keys when the event was generated.

int getModifiers()
Returns a flag indicating the state of all the modifier keys when the event was generated.


Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks