Using shortcut key (or hotkey) to speed up the access to frequently used actions is very common need for every application. We are going to show you some relevant examples of setting shortcut keys in Java Swing programs. 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:

  • 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. The mnemonic letter is underlined in caption of the menu or button.
  • Accelerator: is a key combination (Ctrl key + letter or function key) which is, if pressed, will trigger action listener associated with the menu or button. 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.
The following screenshot shows a typical menu with both mnemonic and accelerator shortcuts:

Typical menu with shortcuts

 

Now, let’s look at some code examples.

1. Set mnemonic key for menu and button

The following statements set mnemonic key ‘F’ for a JMenu:

JMenu menuFile = new JMenu("File");
menuFile.setMnemonic(KeyEvent.VK_F);
And the following statements set mnemonic key ‘O’ for a JMenuItem:

JMenuItem menuItemOpen = new JMenuItem("Open");
menuItemOpen.setMnemonic(KeyEvent.VK_O);
Similarly, setting mnemonic key for a JButton:

JButton button = new JButton("Refresh");
button.setMnemonic(KeyEvent.VK_R);


 

NOTE: The method like setMnemonic(‘R’) is obsolete, so don’t use it.

If you use an Action for the menu item, the setMnemonic() doesn’t work. Instead, you must set mnemonic key via the Action. For example:

JMenuItem menuItemSave = new JMenuItem();

Action saveAction = new AbstractAction("Save") {

	@Override
	public void actionPerformed(ActionEvent e) {
		System.out.println("Saving...");
	}
};

saveAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S);
menuItemSave.setAction(saveAction);
That sets the mnemonic key ‘S’ for the menu Save.


 

2. Set accelerator for menu

The following statements set hotkey for the menu item Open (Ctrl + O):

KeyStroke keyStrokeToOpen
	= KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK);
menuItemOpen.setAccelerator(keyStrokeToOpen);
As you see, the getKeyStroke() method takes two parameters: a character key and a modifier key (Alt, Ctrl or Shift). You can also pass 0 to indicate no modifier is used. For example, the following statements set F3 as hotkey for the menu item:

KeyStroke keyStrokeToOpen = KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0);
In case you use Action to handle click event of the menu item, you have to set accelerator via the action. For example:

JMenuItem menuItemSave = new JMenuItem();

Action saveAction = new AbstractAction("Save") {

	@Override
	public void actionPerformed(ActionEvent e) {
		System.out.println("Saving...");
	}
};

saveAction.putValue(Action.ACCELERATOR_KEY,
		KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK));

menuItemSave.setAction(saveAction);
That sets the key combination Ctrl + S to the Save menu item.

 

 

3. Set application-wide hotkey for button

The following code snippet sets hotkey F5 for a JButton:

JButton button = new JButton();

Action buttonAction = new AbstractAction("Refresh") {

	@Override
	public void actionPerformed(ActionEvent evt) {
		System.out.println("Refreshing...");
	}
};

String key = "Referesh";

button.setAction(buttonAction);

buttonAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R);

button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
		KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), key);

button.getActionMap().put(key, buttonAction);
Here, we use an InputMap and an ActionMap to determine an Action to perform when a keystroke is pressed. The condition WHEN_IN_FOCUSED_WINDOW is used to mean the action should be invoked when the button is in the window that has focus or is itself the focused component. Therefore, the action is always invoked whenever the user presses F5 key when the application has focus (thus application-wide hotkey).

Also note that in the code snippet above, the button is set mnemonic key to ‘R’ key.

 

4. Example Program

For your convenience, we created a demo Swing program that sets up shortcut keys and hotkeys for menu items and button. This program looks like this:

Swing Shortcuts demo

You can download full source code of this program in the Attachment section.

References


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (SwingShortcutKeyDemo.zip)SwingShortcutKeyDemo.zip[Java source code]2 kB

Add comment

   


Comments 

#10wii2020-10-22 03:27
Is there a way that I can put a personolized "string" as a shortcut (for exemple instead of Enter Ent)
Quote
#9Hurukan2020-01-29 15:45
When I want to change the values on a textfield when I push on keyboard ???
How can I do that ?
Must I use non printable key associations jut like F1 to add value F2 to sub ?
Quote
#8Alexandre Desroches2019-09-12 05:32
Cool thank you for the snippets
Quote
#7Dolunay Dagci2019-02-27 17:25
Thank you! It helped me a lot
Quote
#6pa2016-11-10 05:05
Thanks for the code..

But I want to know that if I have to set our own text as shortcut then how should we code..

Because I was comparing it with notepad and its quite different here come Ctrl-N in light and there output is Ctrl+N as normal Font
Quote