final JMenuItem menuItem = new JMenuItem(); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("pressed insert"); } }); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0)); menu.add(menuItem); menuItem.setText("Insert Test");
楼上的是正解,JDK中关于这方法的解释如下,请注意 “Use 0 to specify no modifiers. ”这句话。getKeyStroke public static KeyStroke getKeyStroke(int keyCode, int modifiers)Returns a shared instance of a KeyStroke, given a numeric key code and a set of modifiers. The returned KeyStroke will correspond to a key press. The "virtual key" constants defined in java.awt.event.KeyEvent can be used to specify the key code. For example:java.awt.event.KeyEvent.VK_ENTER java.awt.event.KeyEvent.VK_TAB java.awt.event.KeyEvent.VK_SPACE The modifiers consist of any combination of: java.awt.event.InputEvent.SHIFT_MASK (1) java.awt.event.InputEvent.CTRL_MASK (2) java.awt.event.InputEvent.META_MASK (4) java.awt.event.InputEvent.ALT_MASK (8) Since these numbers are all different powers of two, any combination of them is an integer in which each bit represents a different modifier key. Use 0 to specify no modifiers. Parameters: keyCode - an int specifying the numeric code for a keyboard key modifiers - a bitwise-ored combination of any modifiers Returns: a KeyStroke object for that key See Also: KeyEvent, InputEvent
高位是insert,esc,f1等这些特殊键占用,而低位是ASCII等占用
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("pressed insert");
}
});
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0));
menu.add(menuItem);
menuItem.setText("Insert Test");
“Use 0 to specify no modifiers. ”这句话。getKeyStroke
public static KeyStroke getKeyStroke(int keyCode,
int modifiers)Returns a shared instance of a KeyStroke, given a numeric key code and a set of modifiers. The returned KeyStroke will correspond to a key press.
The "virtual key" constants defined in java.awt.event.KeyEvent can be used to specify the key code. For example:java.awt.event.KeyEvent.VK_ENTER
java.awt.event.KeyEvent.VK_TAB
java.awt.event.KeyEvent.VK_SPACE
The modifiers consist of any combination of:
java.awt.event.InputEvent.SHIFT_MASK (1)
java.awt.event.InputEvent.CTRL_MASK (2)
java.awt.event.InputEvent.META_MASK (4)
java.awt.event.InputEvent.ALT_MASK (8)
Since these numbers are all different powers of two, any combination of them is an integer in which each bit represents a different modifier key. Use 0 to specify no modifiers. Parameters:
keyCode - an int specifying the numeric code for a keyboard key
modifiers - a bitwise-ored combination of any modifiers
Returns:
a KeyStroke object for that key
See Also:
KeyEvent, InputEvent