When trying to apply a listener implementation style using an anonymous or nested class to hide notification methods for purposes other than listening (i.e. I don't want anyone to be able to call actionPerformed). For example, from java action listener: implements vs an anonymous class :
public MyClass() {
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
}
});
}
The question is, is there an elegant way to remove a listener using this idiom? I realized that an instance ActionListenerdoes not create the same objects every time, therefore it Collection.remove()does not delete the originally added object.
To be equal, listeners must have the same appearance. To implement peers, I would need to get an external this for another object. This way it will look like something like this (which I find a bit clumpsy):
interface MyListener {
Object getOuter();
}
abstract class MyActionListener extends ActionListener
implement MyListener {
}
public MyClass() {
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
public Object getOuter() {
return MyClass.this;
}
public boolean equals(Object other)
{
if( other instanceof MyListener )
{
return getOuter() == other.getOuter();
}
return super.equals(other);
});
}
}
Or will I be forced to contain an ActionListener object as a (private) member of an outer class?
source
share