Writing Event Listeners |
Key events tell you when the user is typing 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 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: To generate keyboard events, a component must have the keyboard focus.
To make a component get the keyboard focus, follow these steps:
- Make sure the component can get the keyboard focus. For example, on some systems labels might not be able to get the keyboard focus.
- Make sure that the component requests the focus when appropriate. For custom components, you'll probably need to implement a
MouseListener
that calls therequestFocus
method when the component is clicked.- If you're writing a custom component, implement the component's
isFocusTraversable
method so that it returns true when the component is enabled. This lets the user tab to your component.Key Event Methods
TheKeyListener
interface and its corresponding adapter class,KeyAdapter
, 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.
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.
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:
- Click in the applet's text field so that it gets the keyboard focus.
- 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.- Press the Clear button.
You might want to do this after each of the following steps.- 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.- 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).- 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 generate 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.- 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 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 KeyEvent Class
Each key event method has a single parameter: aKeyEvent
object. TheKeyEvent
class defines the following useful methods:
The
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, andVK_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.
KeyEvent
class inherits many useful methods fromInputEvent
andComponentEvent
. The following methods are described in The MouseEvent Class:
Component getComponent()
void consume()
int getWhen()
boolean isAltDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
int getModifiers()
Writing Event Listeners |