Java Reference
In-Depth Information
Generating User-Defined Events
You can write your own events by performing the following steps:
1.
Write an event class that extends java.util.EventObject.
2.
Write an event listener interface that extends java.util.EventListener.
3.
Add the appropriate add, remove, and get listener methods to your
bean class.
4.
Whenever the event occurs, instantiate an event object and notify all lis-
teners by invoking one of the methods in the event listener interface on
each listener.
Let's look at an example that performs each of these steps. Suppose that we
have a bean named Radio, and we want it to be the source of an event named
volume that is generated each time the volume changes on the radio. Then,
we need to begin by writing a class named VolumeEvent that extends Event-
Object:
public class VolumeEvent extends java.util.EventObject
{
private int volume;
public VolumeEvent(Object source, int volume)
{
super(source);
this.volume = volume;
}
public int getVolume()
{
return volume;
}
}
The corresponding listener interface for VolumeEvent must be named Vol-
umeListener and extend EventListener, as the following interface demon-
strates. Notice that each method has a single parameter of type VolumeEvent.
public interface VolumeListener extends java.util.EventListener
{
public void volumeIncreased(VolumeEvent e);
public void volumeDecreased(VolumeEvent e);
public void muted(VolumeEvent e);
}
Search WWH ::




Custom Search