Keyboard and Mouse Events
More generally, any component, including containers, can generate mouse and keyboard events as the user moves or clicks the mouse in the window, or types a single key on the keyboard.
This is most likely used in a Canvas or graphics drawing area.
Typing a single key generates two KeyEvents. These events must be handled by implementing the KeyListener interface. It has three methods corresponding to the three actions that can occur on a key:
- public void keyPressed (KeyEvent e)
- this is called for an action key, such as arrow keys, home, etc.
- public void keyTyped (KeyEvent e)
- this is called for other keys, such as text characters
- public void keyReleased (KeyEvent e)
- this is called when any key is released
Typically, one uses methods to find the name of the key pressed or typed:
- String s = e.getKeyText (e.getKeyCode());