Application wide keyboard shortcut - Java Swing

Louis Jacomet picture Louis Jacomet · Sep 19, 2008 · Viewed 30.6k times · Source

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?

Answer

Tom Hawtin - tackline picture Tom Hawtin - tackline · Sep 19, 2008

For each window, use JComponent.registerKeyboardAction with a condition of WHEN_IN_FOCUSED_WINDOW. Alternatively use:

JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, command);
JComponent.getActionMap().put(command,action);

as described in the registerKeyboardAction API docs.