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)
From the docs of setMnemonic:
Thus using setMnemonic to do this is impossible.
However, you can use the setAccelerator method defined for
JMenuItem
s, passing a keystroke likeKeyStroke.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.