Nice Books
Nice Books

Reputation: 1861

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?

Upvotes: 4

Views: 8560

Answers (3)

kleopatra
kleopatra

Reputation: 51536

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

Upvotes: 5

David Kroukamp
David Kroukamp

Reputation: 36423

You can add a KeyBinding to your JMenuItem like this:

Action sayHello = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null,"Hello World, From JMenuItem :)");
    }
};
jMenuItem.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F5"),"sayHello");//4.The WHEN_IN_FOCUSED_WINDOW input maps of all the enabled components in the focused window are searched.
jMenuItem.getActionMap().put("sayHello",sayHello);

References:

Upvotes: 4

Reimeus
Reimeus

Reputation: 159874

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.

Upvotes: 12

Related Questions