哪个鼠标按钮是中间的?
2022-09-01 18:36:56
我目前正在Java中开发一个程序,只有当用户单击按钮并单击按钮时,才能触发某个事件。
由于它有点非常规,我决定首先测试一下。在这里:
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 (" ");
}
}
});
}
}
我测试了它,它的工作原理,但有一个问题。
如您所见,鼠标左键由 表示,鼠标右键由 表示。MouseEvent.BUTTON1
MouseEvent.BUTTON3
如果用户的鼠标没有滚轮(显然这样的鼠标仍然存在),那么在MouseEvent中只设置了两个按钮。这是否意味着右键将由 表示,而不是 ?如果是,如何更改代码以适应这种情况?有什么方法可以检测到这样的事情吗?MouseEvent.BUTTON2
MouseEvent.BUTTON3
我阅读了在MouseListener界面和MouseEvent上找到的任何内容,但我找不到有关此内容的内容。