删除匿名侦听器

时间:2015-04-29 11:55:51

标签: java collections listener anonymous

当尝试采用使用匿名或嵌套类实现侦听器的样式时,为了隐藏除侦听之外的其他用途的通知方法(即我不希望任何人能够调用actionPerformed)。例如,来自java action listener: implements vs anonymous class

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

问题是,如果使用这个成语再次删除侦听器是一种优雅的方法吗?我发现ActionListener的实例化每次都不会生成相同的对象,因此Collection.remove()不会删除最初添加的对象。

为了被认为是平等的,听众应该具有相同的外部。为了实现equals,我需要为另一个对象获取外部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对象保留为外部类的(私有)成员?

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:3)

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

不,没有同样优雅的成语可以再次移除听众。唯一的方法是遍历getActionListeners()并删除您想要的那个。当然,如果只有一个就像它一样简单:

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

这不是太难看。

相关问题