Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom Listeners in java?

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.

like image 339
vnshetty Avatar asked Aug 04 '11 12:08

vnshetty


People also ask

How do you add a listener to a class in Java?

You probably want to look into the observer pattern. class Test { public static void main(String[] args) { Initiater initiater = new Initiater(); Responder responder = new Responder(); initiater. addListener(responder); initiater.


2 Answers

https://stackoverflow.com/a/6270150/3675925

You probably want to look into the observer pattern.

Here's some sample code to get you started:

import java.util.*;  // An interface to be implemented by everyone interested in "Hello" events interface HelloListener {     void someoneSaidHello(); }  // Someone who says "Hello" class Initiater {     private List<HelloListener> listeners = new ArrayList<HelloListener>();      public void addListener(HelloListener toAdd) {         listeners.add(toAdd);     }      public void sayHello() {         System.out.println("Hello!!");          // Notify everybody that may be interested.         for (HelloListener hl : listeners)             hl.someoneSaidHello();     } }  // Someone interested in "Hello" events class Responder implements HelloListener {     @Override     public void someoneSaidHello() {         System.out.println("Hello there...");     } } 

 

class Test {     public static void main(String[] args) {         Initiater initiater = new Initiater();         Responder responder = new Responder();          initiater.addListener(responder);          initiater.sayHello();  // Prints "Hello!!!" and "Hello there..."     } } 
like image 90
Hamid Zandi Avatar answered Sep 29 '22 18:09

Hamid Zandi


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.

like image 41
Thomas Avatar answered Sep 29 '22 18:09

Thomas