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?
To add the shortcut keys for an action, click on the action to select the action, then press the keys that you want to associate with the action. To disable the shortcut keys for an action, click on the action to select the action, then press Back Space.
You could simply use: JMenuItem menuItem = new JMenuItem("Refresh"); KeyStroke f5 = KeyStroke. getKeyStroke(KeyEvent. VK_F5, 0); menuItem.
A quick way to switch between open applications is by using the Command + Tab keyboard shortcut. This will display a transparent bar of icons in the middle of your screen. You can keep pressing the shortcut combination to cycle through the open applications on your computer while the bar is displayed on your screen.
Generally, there are two types of shortcut key in Java: Mnemonic: is a single character (usually an alphabet letter from A to Z) which is, if pressed after the Alt key will trigger action listener associated with the menu or button. For example: Alt + F, Alt + O, etc. The associated menu is displayed if mnemonic shortcut is used.
For example: F5, Ctrl + O, Ctrl + F5, etc. The associated menu is not displayed if accelerator shortcut is used. The key combination is displayed next to the menu item.
Because actions are usually triggered by clicking on buttons and menus so it’s very naturally that we bind a shortcut key to a specific button or menu. Generally, there are two types of shortcut key in Java:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With