Which mouse button is in the middle?
I'm currently developing a program in Java where a specific event has to be fired only when the user clicks with the left and right mouse buttons at the same time.
Since this is a bit unconventional, I decided to test it first. here is:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class GUI
{
private JFrame mainframe;
private JButton thebutton;
private boolean left_is_pressed;
private boolean right_is_pressed;
private JLabel notifier;
public GUI ()
{
thebutton = new JButton ("Double Press Me");
addListen ();
thebutton.setBounds (20, 20, 150, 40);
notifier = new JLabel (" ");
notifier.setBounds (20, 100, 170, 20);
mainframe = new JFrame ("Double Mouse Tester");
mainframe.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
mainframe.setResizable (false);
mainframe.setSize (400, 250);
mainframe.setLayout (null);
mainframe.add (thebutton);
mainframe.add (notifier);
mainframe.setVisible (true);
left_is_pressed = right_is_pressed = false;
}
private void addListen ()
{
thebutton.addMouseListener (new MouseListener ()
{
@Override public void mouseClicked (MouseEvent e) { }
@Override public void mouseEntered (MouseEvent e) { }
@Override public void mouseExited (MouseEvent e) { }
@Override public void mousePressed (MouseEvent e)
{
//If left button pressed
if (e.getButton () == MouseEvent.BUTTON1)
{
//Set that it is pressed
left_is_pressed = true;
if (right_is_pressed)
{
//Write that both are pressed
notifier.setText ("Both pressed");
}
}
//If right button pressed
else if (e.getButton () == MouseEvent.BUTTON3)
{
//Set that it is pressed
right_is_pressed = true;
if (left_is_pressed)
{
//Write that both are pressed
notifier.setText ("Both pressed");
}
}
}
@Override public void mouseReleased (MouseEvent e)
{
//If left button is released
if (e.getButton () == MouseEvent.BUTTON1)
{
//Set that it is not pressed
left_is_pressed = false;
//Remove notification
notifier.setText (" ");
}
//If right button is released
else if (e.getButton () == MouseEvent.BUTTON3)
{
//Set that it is not pressed
right_is_pressed = false;
//Remove notification
notifier.setText (" ");
}
}
});
}
}
I tested it and it works, but there is a problem.
As you can see, the left mouse button is represented by and the MouseEvent.BUTTON1
right mouse button is represented by MouseEvent.BUTTON3
.
If the user's mouse doesn't have a scroll wheel (apparently such a mouse still exists), only set two buttons in the MouseEvent. Does this mean that the right button will be MouseEvent.BUTTON2
replaced by MouseEvent.BUTTON3
? If yes, how can I change the code to accommodate this requirement? Is there any way to detect this situation?
I read everything I could find on the MouseListener interface and MouseEvent, but couldn't find anything about it.
To determine which mouse button was pressed, the following three methods from SwingUtilities can help you: