Handling Key Presses in Swing

Below are some notes on handling key presses (keyboard input) in Java. For example if you want Ctrl+Z as an undo action.

First you have to register the keystroke and a handler class for the keystroke:

    InputMap inputMap = this.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK);
    inputMap.put(key, "Undo");
    undoAction = new UndoAction();
    this.getActionMap().put("Undo", undoAction);

Then create the handler class:

class UndoAction extends AbstractAction {
   public void actionPerformed(ActionEvent e) {
      ...  do stuff