Delete anonymous listener

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) {
            //doSomething
        }
    });
}

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) {
            // 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);
        });
    }
 }

Or will I be forced to contain an ActionListener object as a (private) member of an outer class?

+4
source share
2 answers

Assign your anonymous listener to a private local variable, e.g.

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

Later you can use a private variable actionListenerto delete it again.

+3
source

It’s good that the beauty of anonymous classes is that they are anonymous :-)

, , . - getActionListeners() , . , , :

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

.

+3

All Articles