How to get my interface to listen to events?
1 posts in topic
Flat View  Flat View

Posted By:   Anonymous
Posted On:   Wednesday, December 19, 2001 01:10 AM

I have wrote a simple interface and a class that implements my interface.
But now i don't know how to get my class to listen for events.
The events that I'm listening for is datagrams.

How do I get the interface to listen for the events automatically without manually calling the method ?

How do the actionPerformed method in ActionListener listens for any events ?

Thank you in advance.

Re: How to get my interface to listen to events?

Posted By:   Thomas_Rosenbaum  
Posted On:   Wednesday, December 19, 2001 10:28 AM

Try implementing the Observer/Observable design pattern. This pattern allows you to have an observable class that calls a method on any number of observers (listeners) - without knowing who the listeners are. Conversely it also allows any number of observers to 'listen' to any number of observers without having to be coupled to the observable class.

Here is a really brief example:

The Observable class

public class SomeObservableClass implements Observable {

public void someMethod() {
// code ...
String uniqueID = "someID";
this.notifyObservers(this, uniqueID);

private ArrayList observers = new ArrayList();

public void addObserver(Observer observer) {

public void removeObserver(Observer observer) {

private void notifyObservers(String uniqueID){

// Loop through and notify each observer.
Iterator iterator = observers.iterator();

while(iterator.hasNext()) {
Observer observer = (Observer)iterator.next();
observer.registerEvent(this, uniqueID);

The observable interface:

public interface Observable {

private void addObserver(Object observer);

The observer:

public SomeListenerClass implements Observer {

private Observable observableClass;

public SomeListenerClass(Observable observableClass) {
// Subscribe to the Observable class (become an observer).
this.observableClass = observableClass;

The Observer interface:

public interface Observer {

private void registerEvent(Object callingClass, String uniqueID);

To Implement:

// Create a SomeObservableClass object.
SomeObservableClass s = new SomeObservableClass();

// Register an observer.
SomeListenerClass n = new SomeListenerClass(s);

// Then when the first class is called the observer will automatically be listening ...

If this is what you are looking for, there is a great article in JavaWorld on this ...

~ Tom
About | Sitemap | Contact