12

我如何知道从mouseDragged事件中按下的按钮?

我遇到了问题,mouseDragged()因为收到的MouseEvent返回 0 为getButton(). 我对鼠标位置没有问题,甚至检测到鼠标点击。该mouseClicked()事件返回相应的按钮getButton()

关于如何做到这一点的任何建议?我想我可以使用mouseClicked, 或来解决mousePressed这个问题,但我更愿意将这一切都保留在mouseDragged.

感谢您的时间和答案。

4

4 回答 4

23

正如评论和其他答案中所指出的,SwingUtilities 为这种情况提供了三种方法,它们应该适用于所有 MouseEvents:

SwingUtilities.isLeftMouseButton(aMouseEvent);
SwingUtilities.isRightMouseButton(aMouseEvent);
SwingUtilities.isMiddleMouseButton(aMouseEvent);

至于你的方法有什么问题,javadocgetButton()说:

返回哪个鼠标按钮(如果有)已更改状态。

由于按钮的状态在按住时不会改变,因此通常getButton()会返回NO_BUTTON. mouseDragged要检查按钮和修饰符(如Ctrl,Alt等)的状态mouseDragged,您可以使用getModifiersEx(). 例如,以下代码检查BUTTON1已关闭但未关闭BUTTON2

int b1 = MouseEvent.BUTTON1_DOWN_MASK;
int b2 = MouseEvent.BUTTON2_DOWN_MASK;
if ((e.getModifiersEx() & (b1 | b2)) == b1) {
    // ...
}
于 2013-08-11T13:20:16.373 回答
7

雅各布的权利getButton()没有让你按设计获得按钮。但是,我找到了比对 的位操作更清洁的解决方案getModifiersEx(),您也可以在其中使用mouseDragged

if (SwingUtilities.isLeftMouseButton(theMouseEvent)) {
    //do something
}

中键和右键也有类似的方法。

于 2014-06-19T19:05:55.310 回答
2
int currentMouseButton = -1;
@Override
public void mousePressed(MouseEvent e) {
    currentMouseButton = e.getButton();
}

@Override
public void mouseReleased(MouseEvent e) {
    currentMouseButton = -1;
}

@Override
public void mouseDragged(MouseEvent e) {
    if (currentMouseButton == 3) {
        System.out.println("right button");
    }
}
于 2013-12-27T01:00:48.067 回答
0

This could be possibly a problem of your java sandbox.

The following code works well all the time (almost, as you can see).

@Override
public void mouseDragged(MouseEvent e) {
    e.getButton();
}

Please try your code on a different machine.

于 2013-07-03T06:46:38.477 回答