views:

3833

answers:

2

Hello,

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 looks like a brute force solution.

Anyone has a cleaner solution ?

Regards, Louis

+6  A: 

Install a custom KeyEventDispatcher. The KeyboardFocusManager class is also a good place for this functionality.

KeyEventDispatcher

+3  A: 

For each window, use JComponent.registerKeyboardAction with a condition of WHEN_IN_FOCUSED_WINDOW. Alternatively use JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW, true) and JComponent.getActionMap(true) as described in the registerKeyboardAction API docs.

Tom Hawtin - tackline