MouseAdapter方法 - 为什么包括`mouseDragged`,`mouseMoved`和`mouseWheelMoved`?

时间:2013-08-15 18:42:55

标签: java swing mouse-listeners mousemotionevent

我的目标是简化此代码(一切正常):

package test;

import java.awt.Window;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JWindow;

public class A extends JWindow implements MouseListener, MouseMotionListener {

    public A() {
        addMouseListener(A.this);
        addMouseMotionListener(A.this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    }
}

但如果我决定像这样使用MouseAdapter

addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        transferFocusBackward();
        //This method is being used, working fine
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, not working anymore
    }
});

mouseDragged没有收到任何活动。但是如果我像这样添加MouseMotionListener

addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }
});

addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }
});

然后一切都恢复正常。所以我的问题是 - mouseDragged课程中mouseMovedmouseWheelMovedMouseAdapter方法的目的是什么?如果它们不起作用?

1 个答案:

答案 0 :(得分:9)

好吧,我想我现在明白了:在MouseAdapter类文档中,我们说“使用扩展类创建一个侦听器对象,然后使用组件的addMouseListener {{{{ 1}},addMouseMotionListener方法“。现在它看起来像:

addMouseWheelListener

然后:

private class MouseListeners extends MouseAdapter {

    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }
}

现在一切都好。