删除匿名监听器

Removing anonymous listener

当尝试采用匿名或嵌套实现侦听器的风格时 class 以隐藏通知方法以用于侦听以外的其他用途(即我不希望任何人能够调用 actionPerformed ).例如来自 java action listener: implements vs anonymous class:

public MyClass() {
    myButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            //doSomething
        }
    });
}

问题是有没有一种优雅的方法可以使用这个成语再次删除监听器?我发现 ActionListener 的实例化不会每次都产生相同的对象,所以 Collection.remove() 不会删除最初添加的对象。

为了被认为是平等的,听众应该有相同的外部 this。要实现 equals,我需要为另一个对象获取 outer this 。所以它会像这样(我觉得有点笨拙):

interface MyListener {
    Object getOuter();
}

abstract class MyActionListener extends ActionListener
    implement MyListener {
}

public MyClass() {
    myButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // doSomething on MyClass.this
        }
        public Object getOuter() {
           return MyClass.this;
        }
        public boolean equals(Object other)
        {
           if( other instanceof MyListener )
           {
              return getOuter() == other.getOuter();
           }
           return super.equals(other);
        });
    }
 }

或者我是否会被迫将 ActionListener 对象保留为外部 class 的(私有)成员?

将您的匿名侦听器分配给私有局部变量,例如

public MyClass() {
    private Button myButton = new Button();
    private ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //doSomething
        }
    };
    private initialize() {
        myButton.addActionListener(actionListener);
    }
}

稍后可以使用私有变量actionListener再次删除。

这就是匿名的美妙之处 类 - 他们是匿名的 :-)

不,没有类似优雅的成语再次删除侦听器。唯一的方法是遍历 getActionListeners() 并删除你想要的那个。当然,如果只有一个也很简单:

myButton.removeActionListener( myButton.getActionListeners()[ 0 ] );

还不算太丑。