java - Removing anonymous listener -


when trying adopt style of implementing listener using anonymous or nested class in order hide notification methods other uses listening (i.e. don't want able call actionperformed). example java action listener: implements vs anonymous class:

public myclass() {     mybutton.addactionlistener(new actionlistener(){         public void actionperformed(actionevent e) {             //dosomething         }     }); } 

the question if theres elegant way remove listener again using idiom? figured out instantiation of actionlistener not produce equal objects every time collection.remove() won't remove added object.

in order considered equal listeners should have same outer this. implement equals need hold of outer other object. go (which find little 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 forced keep actionlistener object (private) member of outer class?

assign anonymous listener 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 can use private variable actionlistener remove again.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -