Reputation: 21
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?
Upvotes: 2
Views: 277
Reputation: 717
JMenuItem mntmQuit = new JMenuItem("Quit");
mntmQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!(e.getModifiers() == InputEvent.BUTTON3_MASK)) {
System.out.println(e.getActionCommand());
}
}
});
mntmQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0));
Edit:
I've changed my answer, instead of checking for when the event is fired, you should be checking for when to NOT fire it. So in this case, Button3
or right click. The event will always fire when you press "q" or any mouse click.
The previous answer was bad, you don't want to use e.getModifiers()
because it can potentially return true for events that you don't want to return true. e.g. if you had "q" and "w" set to the same button, but they do different things, both events would trigger on the first if
statement checking e.getModifiers() == 0
Sorry for the confusion, hopefully this makes more sense.
Upvotes: 0