繁体   English   中英

MouseListener:确定是否 mousePressed .getSource() == MouseReleased .getSource()

[英]MouseListener: Determine if mousePressed .getSource() == MouseReleased .getSource()

如何检查用户是否在按下鼠标的同一个按钮上释放鼠标?

我想处理用户单击button1 ,继续按住鼠标按钮,然后拖动到button2并在button2上释放鼠标的情况,其中button1button2是我添加了 MouseListeners 的 JButtons。

即:如果用户单击button1 ,然后在button1上释放鼠标,则执行action1()

并且:如果用户单击button1 ,然后在button2上释放鼠标,则什么都不做。

我试过检查ePressed.getSource() == eReleased.getSource() ,但拖动鼠标后源似乎保持不变。

见下文:

// My thoughts are that if the button is released on the source it was
// pressed, it should print "test", however "test" prints even if I 
// drag the mouse outside of the bounds of the button and release it
public JButton getSqaure() {
  JButton jb = new JButton();

  jb.addMouseListener(new MouseAdapter() {
    boolean pressed = false;

    @Override
    public void mousePressed(MouseEvent e) {
      if (SwingUtilities.isRightMouseButton(e)) {
        pressed = true;
      }
    }

    @Override
    public void mouseReleased(MouseEvent e) {
      if (e.getSource() == jb && pressed) {
        System.out.println("test");
      }

      pressed = false;
    }
  });

  jb.setPreferredSize(new Dimension(50,50));

  return jb;
}

当然 - 我已经回答了我自己的问题:

@Override
public void mouseExited(MouseEvent e) {
  pressed = false;
}

@Override
public void mouseEntered(MouseEvent e) {
  pressed = true;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM