So I have to create a simple GUI in Swing for my Java class and I've stumbled upon this minor cosmetic issue.
I have the following code:
JMenuItem mntmQuit = new JMenuItem("Quit");
mntmQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getModifiers() == MouseEvent.BUTTON1_MASK) {
System.out.println("You should fire.");
} else if (e.getModifiers() == MouseEvent.BUTTON2_MASK || e.getModifiers() == MouseEvent.BUTTON3_MASK) {
System.out.println("Why do you fire this event?");
} else {
System.out.println("And how can I catch when the accelerator was used?");
}
}
});
mntmQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0));
I've never seen a menu item that was invoked when right clicking or using any other mouse button than button 1. As it seems Swing sees this differently and sends an action event no matter which mouse button was pressed - in contrary to a JButton
which wont fire anything unless it's clicked with mouse button 1.
Now I could live with that as I can easily catch mouse button 1 and perform my actions, but how about catching the usage of the accelerator? It will fire the action event but I don't see any possibility of catching it as it returns '0' as modifier (same as any other mouse buttons except 1, 2 and 3).
Is there any way that I can tell the JMenuItem
that it should only react to mouse button 1 and it's accelerator? Similar to the way JButton
does it?