我目前正在開發一個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上看到了任何可以找到的東西,但是我找不到這方面的信息。
@PetarMinchev這不會是一個問題,如果我是唯一的用戶......但我會在網上發佈我的程序,很多人可能會使用它(或至少嘗試它)。 –
正確,我只是開玩笑:) –
有3個按鈕鼠標沒有滾輪。 – Ingo