Application-wide keyboard shortcuts in Swing
Posted by Kelvin on 21 Apr 2011 at 11:51 am | Tagged as: programming
Swing's focus subsystem of keyboard events are fired specific to the component in focus.
One way of implementing application-wide keyboard shortcuts is to add it to _every_ component that is created. (yes, its as ridonkulous as it sounds)
Here's another way, using KeyboardFocusManager:
// Add Ctrl-W listener to quit application KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher(){ public boolean dispatchKeyEvent(KeyEvent e) { if (e.getKeyCode() == java.awt.event.KeyEvent.VK_W && e.getModifiers() == java.awt.event.InputEvent.CTRL_MASK) { System.exit(0); return true; } return false; } });