1

I want to use Ctrl instead of Alt for mnemonics of a menu on a menubar. I think it involves using a setAccelerator.

formatMenu.setMnemonic(KeyEvent.VK_F);
sizeMenu.setMnemonic(KeyEvent.VK_X);
styleMenu.setMnemonic(KeyEvent.VK_Z);

This is initalised code which allows me to open the menu but only when I use Alt.

user1870404
  • 31
  • 1
  • 4

1 Answers1

2

Try to use

formatMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));

EDIT: this won't work unless formatMenu is a JMenuItem; for JMenu, setting an accelerator seems not supported natively (at least i have not found any result). A workaround is to implement get/setAccelerator for a menu, like in this SO answer (there it's done for a submenu, but you can modify to suite your needs).

So just do something like the accepted answer there does:

           JMenu formatMenu = new JMenu("Format Menu") {
           private KeyStroke accelerator;

           @Override
            public KeyStroke getAccelerator() {
                return accelerator;
            }

            @Override
            public void setAccelerator(KeyStroke keyStroke) {
                KeyStroke oldAccelerator = accelerator;
                this.accelerator = keyStroke;
                repaint();
                revalidate();
                firePropertyChange("accelerator", oldAccelerator, accelerator);
            }
            };
            formatMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK));
Community
  • 1
  • 1
acostache
  • 2,177
  • 7
  • 23
  • 48
  • java.lang.Error: setAccelerator() is not defined for JMenu. Use setMnemonic() instead. – user1870404 Dec 11 '12 at 12:16
  • corrected my answer - my bad, was not attentive that you were working with JMenu, not JMenuItem – acostache Dec 11 '12 at 12:35
  • did you also add the mnemonics as well as the code above with the accelerator? – acostache Dec 11 '12 at 13:01
  • i used the following: JMenu formatMenu = new JMenu("Format Menu") { private KeyStroke accelerator; public KeyStroke getAccelerator() { return accelerator; } public void setAccelerator(KeyStroke keyStroke) { KeyStroke oldAccelerator = accelerator; this.accelerator = keyStroke; repaint(); revalidate(); firePropertyChange("accelerator", oldAccelerator, accelerator); } }; formatMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK)); formatMenu.setMnemonic(KeyEvent.VK_F); – user1870404 Dec 11 '12 at 13:40
  • i still cant get the menus to use ctrl for mnemonics instead of alt – user1870404 Dec 12 '12 at 02:20