Using Components, the GUI Building Blocks |
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:
- 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.
- 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. 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 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 browser, such as HotJava, the JDK Applet Viewer (appletviewer
), or certain versions of Netscape Navigator and Internet Explorer. For more information about running applets, refer to About Our Examples.
Try this:
- Click in the applet's text field so that it gets the keyboard focus.
- 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.- 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 press (Shift), key press (A), key typed ('A'), key release (A), key release (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 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.- 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
ClassEach key event method has a single parameter: aKeyEvent
object. TheKeyEvent
class defines the following useful methods:
Other potentially useful methods in
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. Also see the
InputEvent
getModifiers
method.KeyEvent
include methods that generate localizable text descriptions of key codes and modifier keys.The
KeyEvent
class extendsInputEvent
, which extendsComponentEvent
.ComponentEvent
provides the handygetComponent
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.
Using Components, the GUI Building Blocks |