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);
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.
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 buttonThe 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.