The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Writing Event Listeners

How to Write a Key Listener

Key events tell you when the user is typing at the keyboard. Specifically, key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys. (For information about focus, see the focus discussion in How to Write 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 handle only 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 -- whether as the result of pressing one key such as 'a' or from pressing several keys in sequence -- you should handle key-typed events. On the other hand, if you want to know when the user presses the F1 key, you need to handle key-pressed events.


Note:  Due to bug # 4186905(outside of the tutorial), text components don't forward key-typed events in JDK 1.2 for Win32.


Note:  To fire 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's isFocusTraversable method returns true. This lets the user tab to your component. For example, you can enable keyboard focus for a custom JLabel subclass by overriding the isFocusTraversable method to return true.
  2. Make sure that the component requests the focus when appropriate. For custom components, you'll probably need to implement a mouse listener that calls the requestFocus method when the component is clicked.
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.

Click this figure to run the applet.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.


Try this: 
  1. Click in the applet's text field so that it gets the keyboard focus.
  2. Type a lowercase 'a' by pressing and releasing 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; key-typed events also don't have modifier information.
  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 fire 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 pressed (Shift), key pressed (A), key typed ('A'), key released (A), key released (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 pressed (Caps Lock), key pressed (A), key typed ('A'), key released (A). Notice that the Caps Lock key doesn't fire a key-released 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(in a .java source file). Here is the applet's key event handling code:

public class KeyEventDemo ...  implements KeyListener ... {
    ...//where initialization occurs:
	typingArea = new JTextField(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 Key Event API

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 just after the user types a Unicode character into the listened-to component.
void keyPressed(KeyEvent)
Called just after the user presses a key while the listened-to component has the focus.
void keyReleased(KeyEvent)
Called just after the user releases a key while the listened-to component has the focus.
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. You can get the state of the modifier keys using InputEvent getModifiers method.

String getKeyText()
String getKeyModifiersText()
Return text descriptions of the event's key code and modifier keys, respectively.
The KeyEvent class inherits many useful methods from InputEvent(in the API reference documentation) and ComponentEvent(in the API reference documentation). The following methods are described in The MouseEvent Class:

Examples that Use Key Listeners

The following table lists the examples that use key listeners.

Example Where Described Notes
KeyEventDemo This section Reports all key events that occur on a text field to demonstrate the circumstances under which key events are fired.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.