# Java Notes: Keyboard

Not normally used. You don't normally need to capture the low-level keyboard events because components (eg, `JTextField`) handle them for you. One of the few cases where you might want to handle them is in a subclass of JPanel that is being used for graphics where key strokes need to be interpreted, eg, to move an image, fill in a crossword cell, etc.

There are three types of characters, each of which is handled differently, altho they all generated pressed and released events.

1. Characters (a, A, #, ...) - handled in the `keyTyped()` listener.
2. Virtual keys (arrow keys, function keys, etc) - handled with `keyPressed()` listener.
3. Modifier keys (shift, alt, control, ...) - Usually their status (up/down) is tested by calls in one of the other listeners, rather than in `keyPressed()`.

Warning: This was written for Java 1.2. In more recent versions (1.3+) javax.swing.InputMap should be used in preference to KeyListener for getting characters. Eventually I'll rewrite these notes.

## Listener Classes and Interfaces

The `java.awt.event.KeyListener` interface and `java.awt.event.KeyEvent` class are all imported by:

    import java.awt.event.*;

### `KeyTyped()` versus `KeyPressed()` and `KeyReleased()`

Three methods must be defined in a class that implements KeyListener:

`keyTyped(KeyEvent e)`
  The `KeyTyped()` listener method is called when a character is typed, but is not useful for virtual keys (arrow keys, function keys, etc). Modifier key (shift, control, etc) status (up/down) can be tested with method calls in the listener.
`keyPressed(KeyEvent e)` and `keyReleased(KeyEvent e)`
  These methods are called whenever any key is pressed or released. Regular character keys also produce calls to these listeners, but are usually handled by the `keyTyped()` listener and may be ignored in this listener. Modifier keys (shift, control) also generate calls to these listeners, but are typically tested with method calls in the listener. For example, if you type an uppercase 'J', there are five events, which call these methods:
  1. KeyPressed for pressing the shift key.
  2. KeyPressed for pressing the j key.
  3. KeyTyped for the character J.
  4. KeyReleased for releasing the j key.
  5. KeyReleased for releasing the shift key.

## Focus - Which component gets KeyEvents? -- The one with Focus

The key listener for your JPanel is called only if the JPanel has focus. Only one component has focus at a time, not all components can get focus, and key events are directed to the component with focus.

### Make your panel focusable, then request focus.

Not all components can get focus, eg labels do not get focus. To ensure that your JPanel subclass can get focus, call `setFocusable()` in the constructor (note: it can only help, altho I've written programs where it didn't appear to be necessary.).

    this.setFocusable(true);   //  In panel constructor.

After you have build the graphical user interface, give the panel p focus with:

    p.requestFocus();

When your window is active, all key events will be given to the listeners for your panel p.

### Example - Key listeners in a JPanel subclass

You can place a key listener in your JPanel subclass. For example

    class MyPanel extends JPanel implements KeyListener {
        . . .
        //=================================== constructor
        public MyPanel() {
           this.setFocusable(true);   // Allow this panel to get focus.
           this.addKeyListener(this); // listen to our own key events.
           . . .
        }

        //-- Define one or more of these to handle keyboard events
        public void keyPressed(KeyEvent e) {. . .}
        public void keyReleased(KeyEvent e){. . .}
        public void keyTyped(KeyEvent e)   {. . .}
    }

### Example - To get a character that is typed

You need to add a key listener to your panel. A key listener has three methods for handling events, but you only need to do something in the `keyTyped` method if you want to get the character that was typed. Here is a listener that adds all characters that are typed to the string s.

    public void keyTyped(KeyEvent e) {
        s = s + e.getKeyChar();
    }

# Virtual Keys

Many keys do not generate characters, for example, the shift, arrow, or function keys. These keys generate a virtual key code that you can check in the `keyPressed()` (but not `keyTyped()`) listener.

### Use `keyPressed(...)` or `keyReleased(...)`, not `keyTyped(...)`

There is no character for many keys, so you can not use the `KeyTyped()` listener method. You must write the `KeyPressed(...)` or `KeyReleased(...)` listener methods to find out when these keys are used.

## To get the virtual key code

se the KeyEvent.getKeyCode() method to get the virtual key code. For example,

    public void keyPressed(KeyEvent ke) {
        switch (ke.getKeyCode()) {
        case KeyEvent.VK_LEFT:  // move x coordinate left
            x -= dx;
            x = Math.max(x, 0);
            break;
        case KeyEvent.VK_RIGHT: // move x coordinate right
            x += dx;
            x = Math.min(x, 100);
        }
        drawing.repaint();
    }

### Virtual Key Codes

The `KeyEvent` class defines a large number of virtual key codes that correspond keys on the keyboard. This list may expand as new keyboards are supported. See the `java.awt.event.KeyEvent` documentation for a list of these. Below are some of the most common codes. You can probably figure out the key from the name.

Alphanumeric keys
  VK_0, VK_1, ..., VK_9, VK_A, VK_B, ..., VK_Z
Control keys
  VK_ENTER, VK_BACKSPACE, VK_TAB, VK_ESCAPE
Function keys
  VK_F1, VK_F2, VK_F3, VK_F4 VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12,
  VK_SCROLL_LOCK, VK_PRINTSCREEN, VK_PAUSE,
  VK_DELETE, VK_INSERT,
  VK_PAGE_UP, VK_PAGE_DOWN, VK_HOME, VK_END
Arrow keys
  VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN

# Testing Modifier Keys

Certain keys are used as modifier keys to change another action. For example, holding the ALT key down while clicking on the mouse may alter the action you want to perform. The event object has methods which may be called to find the status (up/down) for these modifier keys. MouseEvent and KeyEvent are both subsets of `java.awt.event.InputEvent`, so either can use these methods for determining which modifier keys are pressed.

### Testing Modifier Keys from an Event Object

The following methods are available for KeyEvent and MouseEvent objects (e), and would normally be used inside of a mouse or key listener.

`e.isAltDown()` | `true` if the ALT key was down when this event happened.
`e.isControlDown()` | `true` if the CTRL key was down when this event happened.
`e.isShiftDown()` | `true` if the SHIFT key was down when this event happened.
`e.isMetaDown()` | `true` if the META key was down when this event happened.
`e.isAltGraphDown()` | `true` if the ALT-GRAPH key was down when this event happened.
`e.getModifiers()` | This method returns an int bit mask which identifies the keys and mouse buttons which are down at the time of the event. Many constants are defined to test these. Some of the more common are:
`InputEvent.ALT_MASK` | ALT key is down.
`InputEvent.CTRL_MASK` | CTRL key is down.
`InputEvent.SHIFT_MASK` | SHIFT key is down.
`InputEvent.ALT_GRAPH_MASK` | ALT-GRAPH key is down.
`InputEvent.META_MASK` | META key is down.
`InputEvent.BUTTON1_MASK` | Mouse button 1 is down.
`InputEvent.BUTTON2_MASK` | Mouse button 2 is down.
`InputEvent.BUTTON3_MASK` | Mouse button 3 is down.

## Examples

- Example - KeyDemo - Shows use of KeyListener.