How can I listen for key presses (within Java Swing) across all components?

It is possible.

KeyboardFocusManager.getCurrentKeyboardFocusManager()
  .addKeyEventDispatcher(new KeyEventDispatcher() {
      @Override
      public boolean dispatchKeyEvent(KeyEvent e) {
        System.out.println("Got key event!");
        return false;
      }
});

That will grab all key events. Returning false allows the keyboard focus manager to resume normal key event dispatching to the various components.

If you want to catch key combos, you can keep a set of “pressed keys.” Whenever a key is pressed, add it to the set and check what keys are already in the set. When a key is released, remove it from the set.

Leave a Comment