java - MouseListener:判断是否 mousePressed .getSource() == MouseReleased .getSource()

标签 java swing mouseevent mouselistener

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

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

That is: if the user clicks button1, and releases the mouse on button1, do action1().

And: if the user clicks button1, and releases the mouse on button2, do nothing.

我尝试检查是否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;
}

关于java - MouseListener:判断是否 mousePressed .getSource() == MouseReleased .getSource(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108100/

相关文章:

java - 使用 jtable 生成表运行时和鼠标单击事件

java - 如何使用 ThreadPoolExecutor 和自定义任务实现 PriorityBlockingQueue

java - 在 JFrame 中显示 JPanel 的内容

java - JTable多选不使用键盘只使用鼠标

java - 我的 JSpinner 不更改也不接受我对其所做的任何更改

java - 如何使用MouseEvent?

java - 是否需要 try catch block

java - 如何在 2 个池线程之间同步数组的切换?

java - 使用JAVA创建数据库postgresql

javascript - 网站如何最终破坏中键点击功能?