如果按住两个鼠标按钮,然后拖动鼠标,然后释放任一按钮,如何确定释放了哪个按钮?按下的按钮可以使用MouseEvent.getModifiersEx()检索,但似乎没有任何方法可以告诉哪一个被释放,因为在释放事件触发器之前按下的所有按钮都存储在该掩码中:
public void mouseReleased(MouseEvent e) {
int b1 = MouseEvent.BUTTON1_DOWN_MASK;
int b2 = MouseEvent.BUTTON2_DOWN_MASK;
System.out.println(e.getButton()) // prints "0" when the mousereleased
// event follows a mouseDragged
// event
if ((mouseEvent.getModifiersEx() & b1) == b1) {
System.out.println("button 1 released");
} else if ((mouseEvent.getModifiersEx() & b2) == b2) {
System.out.println("button 2 released");
}
/*
Following a mouseDragged event, assuming button 1 and button 2
were pressed before either was released, the first if clause
evaluates to true regardless of which button was actually released.
In other words, releasing button 2 in this scenario will print
"button 1 released"
*/
}
如果mouseReleased事件前面有一个mousePressed事件,但是当它之前是mouseDragged时,我很容易调用getButton()......
答案 0 :(得分:1)
但是当它以mouseDragged开头时,我不能简单地调用getButton()......
为什么不呢?
如果您想在拖动停止后释放鼠标的状态,可以在MouseAdapter中使用布尔标志并在拖动时将其设置为true。类似的东西:
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class MouseButtons extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
public MouseButtons() {
MyMouseAdapter myMouse = new MyMouseAdapter();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
private boolean dragging = false;
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
String text = "";
int button = e.getButton();
if (button == MouseEvent.BUTTON1) {
text = "Button 1";
} else if (button == MouseEvent.BUTTON2) {
text = "Button 2";
} else if (button == MouseEvent.BUTTON3) {
text = "Button 3";
}
if (dragging) {
System.out.println(text + " just finished dragging");
} else {
System.out.println(text + " not recently dragging");
}
dragging = false;
}
@Override
public void mouseDragged(MouseEvent e) {
dragging = true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("MouseButtons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MouseButtons());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
除非我完全误解你的问题,如果是,那么我请你澄清一下。