I would like to create an application wide keyboard shortcut for a Java Swing application. Looping over all components and adding the shortcut on each, has focus related side effects, and seems like a brute force solution.
Anyone has a cleaner solution?
For people wondering (like me) how to use KeyEventDispatcher, here is an example that I put together. It uses a HashMap for storing all global actions, because I don't like large
if (key == ..) then .. else if (key == ..) then .. else if (key ==..) ..
constructs.The use of SwingUtils.invokeLater() is maybe not necessary, but it is probably a good idea not to block the global event loop.
Install a custom KeyEventDispatcher. The KeyboardFocusManager class is also a good place for this functionality.
KeyEventDispatcher
Use the following piece of code
Replace "ctrl D" with the shortcut you want.
For each window, use
JComponent.registerKeyboardAction
with a condition ofWHEN_IN_FOCUSED_WINDOW
. Alternatively use:as described in the registerKeyboardAction API docs.
A little simplified example:
When you have a menu, you can add global keyboard shortcuts to menu items: