Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application wide keyboard shortcut - Java Swing

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?

like image 561
Louis Jacomet Avatar asked Sep 19 '08 06:09

Louis Jacomet


People also ask

How do I add a keyboard shortcut in Java?

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.

How do I add a shortcut to JMenuItem?

You could simply use: JMenuItem menuItem = new JMenuItem("Refresh"); KeyStroke f5 = KeyStroke. getKeyStroke(KeyEvent. VK_F5, 0); menuItem.

What is the keyboard method to move through open applications?

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.

What are the types of shortcut keys in Java?

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.

What is the shortcut key combination for the accelerator?

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.

Why do we bind a shortcut key to a button?

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:


1 Answers

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.

like image 81
Tom Hawtin - tackline Avatar answered Sep 23 '22 04:09

Tom Hawtin - tackline