java.awt.event.KeyEvent
is sent to a component when a key is pressed while the
component has the focus. There are three types of key events, each represented by an integer constant:
KeyEvent.KEY_PRESSED | A key was pressed |
KeyEvent.KEY_RELEASED | A key was released |
KeyEvent.KEY_TYPED | A key press followed by a key release. |
Most of the time you'll only respond to the last event, KeyEvent.KEY_TYPED.
The main thing you want to know about a KeyEvent
is what key was pressed. You get this with the getKeyChar()
method.
public char getKeyChar()
This returns the Unicode character corresponding to the pressed key.
A KEY_PRESSED or KEY_RELEASED event doesn't just have a character. It also has a key code. (KEY_TYPED events do not have key codes. More precisely the key code is undefined.)
If you're concerned about the key that was pressed, rather
than the character that was typed, you'll ask the key event
for its key code rather than its key char. You get the code for a KeyEvent
by calling getKeyCode()
:
public int getKeyCode()
You can convert this into a localized string such as "END", "F4" or "Q"
by passing it to the static method, KeyEvent.getKeyText()
:
public static String getKeyText(int keyCode)
Generally you respond to key events directed at your component, by registering
a KeyListener
object with the component. The KeyListener
interface defines the following methods, one for each type of KeyEvent
.
public abstract void keyTyped(KeyEvent e)
public abstract void keyPressed(KeyEvent e)
public abstract void keyReleased(KeyEvent e)