Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a single key shortcut to a JMenuItem

I am creating a simple text editor similiar to Notepad. It would insert the time and date to the file if the user presses F5. I browsed about mnemonics and accelerators but they are used in combination with Alt and Ctrl respectively.

Should I use an EventListener or is there any other solution?

like image 951
Nice Books Avatar asked Nov 30 '22 05:11

Nice Books


2 Answers

You could simply use:

JMenuItem menuItem = new JMenuItem("Refresh");
KeyStroke f5 = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
menuItem.setAccelerator(f5);

with KeyStroke having 0 specifying no modifiers as described in the docs.

An ActionListener is the appropriate listener for menu item events.

like image 187
Reimeus Avatar answered Dec 02 '22 18:12

Reimeus


As partly already mentioned in some comments, the recommended approach is

  • use an action to configure a menuItem
  • configure the action with an accelerator
  • add the action to the menu

Some code:

Action doLog = new AbstractAction("Dummny log!") {

    @Override
    public void actionPerformed(ActionEvent e) {
        LOG.info("doing: " + getValue(Action.NAME));
    }
};
doLog.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F5"));

JMenu menu = new JMenu("dummy");
menu.add(doLog);
frame.getJMenuBar().add(menu);
like image 30
kleopatra Avatar answered Dec 02 '22 20:12

kleopatra