9

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

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上的目的mouseMovedmouseWheelMoved方法是什么?MouseAdapter

4

1 回答 1

10

好的,我想我现在明白了:在MouseAdapter类文档中说“使用扩展类创建一个侦听器对象,然后使用组件的addMouseListener, 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
    }
}

接着:

MouseListeners listeners = new MouseListeners();   
addMouseListener(listeners);
addMouseMotionListener(listeners);

现在一切正常。

于 2013-08-15T19:04:49.737 回答