I have a user request to add an accelerator to a sub menu (JMenu) which would allow the user to press the short cut and have the corresponding sub menu "fold out", showing its contained menu items.
I don't recall every having seen something like this (either in Java or any other language). Our application is written in Java using Swing. We have a number of JMenuItems with accelerators that work well, but when I attempted to add an accelerator to JMenu I get the following exception:
java.lang.Error: setAccelerator() is not defined for JMenu. Use setMnemonic() instead.
I've tried to use the MenuDemo! code to experiment with this a bit further.
This is what I tried:
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEvent.VK_S);
submenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK));
The last line is the one added by me, which causes the exception.
I've tried extensive googling but all I can find is articles on how to add accelerators to JMenuItem.
It seems the JMenu does not support this natively. Is there any workaround to achieve this behaviour?
I don't think that is possible just like that. But what you could do is adding an
AbstractAction
, which simulates a click.I hope this also works for you.
Another option is to override the accelerator get/set and reproduce the JMenuItem behaviour. Then the UI will do the rest of the job.
The important thing is to fire the property change and have a consistent get/set for the accelerator. The advantage of this solution is that it also provides a visual indication of the shortcut/accelerator.
Here is a small demo code: