java swing同时拥有两个鼠标按钮

时间:2013-04-11 19:21:39

标签: java swing mouselistener mouseleftbuttondown right-mouse-button

我想实现一种方法,用户需要同时按住鼠标左键和右键。

我正在使用Swing和Java 1.7。我试过这个,但它并没有像我期望的那样检测到双按钮的情况:

public void mousePressed(MouseEvent e) {    
     if (SwingUtilities.isLeftMouseButton(e) && SwingUtilities.isRightMouseButton(e)){
              ///code here
     }
}

我试图分离方法并使用bool值来决定是否按下了鼠标按钮然后我设置了一个条件来确定它们是否同时被按下了,但是这样做也没有用。

2 个答案:

答案 0 :(得分:6)

这是一个做你想要的SSCCE ...即如果我理解你的问题。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class StackOverflow15957076 extends MouseAdapter
{
    private JLabel status;

    private boolean isLeftPressed;
    private boolean isRightPressed;

    public StackOverflow15957076 ()
    {
        JFrame frame = new JFrame ();
        frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

        JPanel panel = new JPanel (new FlowLayout (FlowLayout.CENTER));

        status = new JLabel ("waiting for both mouse buttons...");

        status.addMouseListener (this);

        panel.add (status);

        frame.add (panel);

        frame.pack ();
        frame.setVisible (true);

        isLeftPressed = false;
        isRightPressed = false;
    }

    @Override
    public void mousePressed (MouseEvent e)
    {
        if (SwingUtilities.isLeftMouseButton (e))
        {
            isLeftPressed = true;
        }
        else if (SwingUtilities.isRightMouseButton (e))
        {
            isRightPressed = true;
        }

        if (isLeftPressed && isRightPressed)
        {
            status.setText ("both buttons are pressed");
        }
    }

    @Override
    public void mouseReleased (MouseEvent e)
    {
        if (SwingUtilities.isLeftMouseButton (e))
        {
            isLeftPressed = false;
        }
        else if (SwingUtilities.isRightMouseButton (e))
        {
            isRightPressed = false;
        }

        status.setText ("waiting for both mouse buttons...");
    }

    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable ()
        {
            @Override
            public void run ()
            {
                new StackOverflow15957076 ();
            }
        });
    }
}

答案 1 :(得分:1)

似乎不可能直接执行,因为鼠标事件是按顺序触发的。例如,请参阅this SO question/answers

因此,您需要确定“同时”对您实际意味着什么(即,应该在多长时间内完成)。然后,您可以捕获两个单独的事件并比较它们的getWhen()值。