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?
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.
As partly already mentioned in some comments, the recommended approach is
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With