some questions about setMnemonic

1k views Asked by At

I have the code:

public class MenuBar extends JFrame {

    public MenuBar() {
        initUI();
    }

    public final void initUI() {

        JMenuBar menubar = new JMenuBar();

        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);

        JMenuItem eMenuItem = new JMenuItem("Exit");
        JMenuItem oMenuItem = new JMenuItem("Open Another");
        eMenuItem.setMnemonic(KeyEvent.VK_E);
        oMenuItem.setMnemonic(KeyEvent.VK_O);
        eMenuItem.setToolTipText("Exit application");
        oMenuItem.setToolTipText("Open another Window");
        eMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }
        });
        oMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                main(null);
            }
        });

        file.add(eMenuItem);
        file.add(oMenuItem);
        menubar.add(file);

        setJMenuBar(menubar);

        setTitle("Simple menu");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MenuBar ex = new MenuBar();
                ex.setVisible(true);
            }
        });
    }
}

it works fine but I had a question about setMnemonic. How would you go about making the Mnemonic for eMenuItem just to press E, as opposed to Alt + E? Thanks for any and all help! (Please not I left imports out intentially, for length issues)

2

There are 2 answers

3
Sinkingpoint On BEST ANSWER

From the docs of setMnemonic:

The mnemonic is the key which when combined with the look and feel's mouseless modifier (usually Alt) will activate this button if focus is contained somewhere within this button's ancestor window.

Thus using setMnemonic to do this is impossible.

However, you can use the setAccelerator method defined for JMenuItems, passing a keystroke like KeyStroke.getKeyStroke('e');

Alternatively, you could, as Joop Eggen pointed out in the comments to this answer use a MenuKeyListener which allows for greater control over the specific events that the action is performed on.

1
noMAD On

I don't know if this would work but you can try it out. From this (http://docs.oracle.com/javase/7/docs/api/constant-values.html#java.awt.event.KeyEvent.VK_E) we see that the ASCII binding for VK_E is 69. This is caps E. To get the one for small e its 101, which corresponds to VK_NUMPAD5. I might be wrong though, its just a guess.