How do you make menu item (JMenuItem) shortcut?

Adrian Hristov picture Adrian Hristov · Nov 13, 2012 · Viewed 23.4k times · Source

So i noticed that in awt there is a MenuItem constructor for adding a CTRL + (some key) shortcut, but there is no such constructor for JMenuItem. What is the correct way to do this?

I need an equivelent of awt:

MenuItem mi = new MenuItem("Copy", new MenuShortcut(KeyEvent.VK_C));

but for Swing.

Answer

Dan D. picture Dan D. · Nov 13, 2012

Example for CTRL + N.

menuItem.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));

Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask() returns control key (ctrl) on Windows and linux, and command key (⌘) on Mac OS.