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

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方法不起作用,它们的目的是什么?

最佳答案

好的,我想我现在已经明白了:在MouseAdapter类文档中,它说“使用扩展类创建一个监听器对象,然后使用该组件的addMouseListeneraddMouseMotionListeneraddMouseWheelListener方法在一个组件中注册它”。所以现在看起来像:

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
    }
}

然后:
MouseListeners listeners = new MouseListeners();
addMouseListener(listeners);
addMouseMotionListener(listeners);

现在一切正常。

10-07 16:40