
Fire Events and Stay Bug Free #94
Chapter 12, Miscellany
|
473
HACK
The Problem
To illustrate the problem and its various solutions, consider the listener class
in Example 12-11.
This listener hangs on to a
String and prints that string to standard out
when
handleEvent( ) is called. Also, if the string is a specific value—C in this
case—it removes itself from the event source. If you can see why that’s going
to be a big deal, congratulations. If not, read on.
Next, define an abstract class to exercise various means of firing the event.
This is shown in Example 12-12.
This abstract class requires subclasses to include
addListener( ),
removeListener( ), and fireEvent( ) methods. It also implements a test
method that creates five listeners, identified as the letters
A through E, and
fires an event to each one.
Example 12-11. A simple event listener
import java.util.*;
public class TestEventListener extends Object
implements EventListener {
String id;
public TestEventListener (String id) {
this.id = id;
}
public void handleEvent (EventObject o) {
System.out.println (id + " called");
if (id.equals ("C")) {
((TestEventSource) o.getSource( )).removeListener (this);
}
}
}
Example 12-12. Abstract class for testing event-firing techniques
public abstract class TestEventSource {
public abstract void addListener (TestEventListener l);
public abstract void removeListener (TestEventListener l);
public abstract void fireEvent ...