私は現在、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には2つのボタンしか設定されません。これは、MouseEvent.BUTTON3
ではなく、右ボタンがMouseEvent.BUTTON2
で表されることを意味しますか?はいの場合、これに対応するためにコードをどのように変更できますか?このような何かを検出できる方法はありますか?
私はMouseListenerインターフェイスとMouseEventで何かを見つけることができましたが、これについては何も見つかりませんでした。
@PetarMinchevこれは私が唯一のユーザーだった場合には問題にはならないかもしれませんが、私は自分のプログラムをオンラインで公開するので、おそらく多くの人がそれを使用するでしょう(少なくとも試してみてください)。 –
正解、私はちょうど冗談を言っていました:) –
スクロールホイールのない3つのボタンマウスがあります。 – Ingo