JMenu accelerators and mnemonics Example
This JMenu example shows how to apply accelerators and mnemonics to a menu. A mnemonic can be used to drop down a menu and a further mnemonic is used to select a menu item on it. This will involve minimally two keystrokes.
An accelerator is a keystroke combination that is unique across the menubar and can be used at any time to invoke the menu item associated with the keystroke combination.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// JMenu Accelerators Mnemonics Example
import java.awt.*; import java.awt.event.*; import javax.swing.*;
class JMenuAccelerators extends JFrame implements ActionListener {
public void actionPerformed (ActionEvent e) {
System.out.println(e.getActionCommand());
}
public JMenuAccelerators() {
super();
JMenu menu = new JMenu("File");
JMenuItem printM = new JMenuItem("Print");
JMenuItem previewM = new JMenuItem("Print preview");
JMenuItem exitM = new JMenuItem("Exit");
menu.add(printM); menu.add(previewM);
menu.add(new JSeparator());menu.add(exitM);
printM.addActionListener(this);
previewM.addActionListener(this);
exitM.addActionListener(this);
menu.setMnemonic(KeyEvent.VK_F);
printM.setMnemonic(KeyEvent.VK_P);
exitM.setMnemonic(KeyEvent.VK_X);
printM.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK));
previewM.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_P,
Event.CTRL_MASK+Event.SHIFT_MASK));
exitM.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK));
JMenuBar bar = new JMenuBar();
bar.add(menu); setJMenuBar(bar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(150,200); setVisible(true);
}
public static void main(String[] args) {
new JMenuAccelerators();
}
}
21-23 You will notice that the menu item 'File' in the menubar has its letter 'F' underlined. This is because the character 'F' was chosen as a mnemonic for it. The user can select it by keying alt-F.
Similarly, 'P' and 'X' have been chosen as mnemonics for menu items below it. These mnemonics can only be used after the menu has been selected.
25-31 These menu items have been assigned accelerator keystrokes.
Accelerators can be keyed at any time to invoke the associated menu item.
Accelerators must therefore be unique across the menubar.
