How to create custom Listeners in java?

vnshetty picture vnshetty · Aug 4, 2011 · Viewed 53.6k times · Source

I want to know about how to set our own Listeners in java.For example I have a function that increments number from 1 to 100. i want to set a listener when the value reaches 50. How can i do that? Pls suggest me any tutorial.

Answer

Thomas picture Thomas · Aug 4, 2011

Have a look at the source of any class that uses listeners. In fact it's quite easy:

  • create an interface for your listener, e.g. MyListener
  • maintain a list of MyListener
  • upon each event that the listeners should listen to, iterate over the list and call the appropriate method with some event parameter(s)

As for the observer pattern along with some Java code have a look at wikipedia.