I have tried setting the accelerator of a JMenuItem
using the following :
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
The menu item shows the shortcut ⌘+
(on a mac) but hitting these two keys won't trigger it. I have the same problem with the minus sign -
.
I开发者_StackOverflows there any way to have a menu item with any of these signs as a shortcut ?
EDIT - Here is a SSCCE :
public class MenuWithPlus {
public static void main(String[] args) {
JFrame frame = new JFrame();
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("View");
JMenuItem item = new JMenuItem("Zoom in");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("ZOOM IN TRIGGERED");
}
});
menu.add(item);
bar.add(menu);
frame.setJMenuBar(bar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
At accelerator code you have to modify to:
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, Event.CTRL_MASK));
A test that I made was add a key event listener on frame and catch de key value for plus (in this case ADD).
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyCode());
}
});
Are you using the +/- keys on the main keyboard vs. the numpad? They're seen as separate keys, so make sure you're using them consistently.
I think VK_PLUS
is not used for the usual plus key (Shift-= on a US keyboard), but rather either the numpad +, or the + key on some German keyboards. Assuming you have a US keyboard, you might want Shift together with VK_EQUALS
.
See this old bug and this discussion.
精彩评论