如何在一个侦听器中识别mouseDragged和mousePressed事件?

时间:2010-02-21 19:27:18

标签: java swing mouse listener

在以下代码中,无法识别mouseDragged。我做错了什么?

addMouseListener(new MouseInputAdapter() {

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

});

3 个答案:

答案 0 :(得分:7)

MouseInputAdapter mia = new MouseInputAdapter() {
  @Override
  public void mouseDragged(MouseEvent e) { ... }
  @Override
  public void mousePressed(MouseEvent e) { ... }
};
addMouseListener(mia);
addMouseMotionListener(mia); // <-- You're missing this one.

答案 1 :(得分:4)

由于您正在mouseDragged内部实施addMouseListener,因此无法识别。

mouseDraggedMouseMotionListener触发,mousePressedMouseListener触发。

因此,您需要实现MouseListenerMouseMotionListener并相应地添加正确的侦听器。

public class MyClass extends JPanel implements MouseListener,
                                               MouseMotionListener {

  public MyClass() {
    // whatever code you need, then add the listeners
    this.addMouseListener(this); 
    this.addMouseMotionListener(this);
   }

  public void mousePressed(MouseEvent e) { ... }
  public void mouseDragged(MouseEvent e) { ... }

}

答案 2 :(得分:0)

不要使用addMouseListener,而是使用addMouseMotionListener:

addMouseMotionListener(new MouseMotionListener() {

        @Override
        public void mouseMoved(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseDragged(MouseEvent e) {
            // TODO Auto-generated method stub

        }
    });

:d