哪个鼠标键位于中间?
我目前正在用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上可以找到的所有内容,但是却找不到任何相关信息。
回答:
要确定按下了哪个鼠标按钮,SwingUtilities的以下三种方法可以帮助您:
- isLeftMouseButton
- isMiddleMouseButton
- isRightMouseButton
以上是 哪个鼠标键位于中间? 的全部内容, 来源链接: utcz.com/qa/403506.html