Home >> Java
Event handling and Java Technology
How can I extend Java event handling code to suite application
specific event handling?
There are four parts to event handling, one is listener, second
one is event object, the third one is the event container and
fourth one is the event propagator.
Extension point for first two parts are provided by
Java api as java.util.EventListener and java.util.EventObject
respectively. The third one (Event listener container) and
fourth one (event generator) has to be provided by programmer
Event generator should extend event listener container,
and every event generator/source should add event listeners
added to it, and calls event methods and passes event object
associated with this event listener.
|
|  |
|
Let us implement a sample demo exercise:
A demo listener implemented as follows:
The first one is the event listener as follows:
-----------------------------------------------------------------
public interface DemoListener extends
java.util.EventListener
{
public void demoEvent(DemoEvent dm);
}
-----------------------------------------------------------------
and second one the event object as follows:
-----------------------------------------------------------------
public class DemoEvent extends java.util.EventObject
{
Object obj;
public DemoEvent(Object source)
{
super(source);
obj = source;
}
public Object getSource()
{
return obj;
}
......
}
-----------------------------------------------------------------
The third part is the event container:
-----------------------------------------------------------------
public class EventContainer
{
private Vector repository = new Vector();
DemoListener dl;
public EventContainer()
{
}
public void addDemoListener(DemoListener dl)
{
repository.addElement(dl);
}
public void notifyDemoEvent()
{
Enumeration enum = repository.elements();
while(enum.hasMoreElements())
{
dl = (DemoListener)enum.nextElement();
dl.demoEvent(new DemoEvent(this));
}
}
......
}
-----------------------------------------------------------------
The fourth one is the event listener implementor, that
implements event listener and implements event handling
code/method.
EventContainer adds implemented DemoListener and based
on certain event, notifyDemoEvent methods executes
demoEvent method for all the demo listeners in the
repository inside EventContainer.
If you like to share your comment/suggestions/feedback relating to this Page,
you can do so by droping us an email at
usingframeworks @ gmail . com
with the subject line mentioning URL for this Page (i.e,
/event-handling-java-code.php) or use this
LINK.
As per this website's privacy policy, we never disclose your email id,
though we shall post your comments/suggestions/feedback with
your name (optional) and date on this Page. If you don't want your
comments/suggestions/feedback to be shared in this Page, please
mention so in your email to us. Thank you very much.....
If anything missed out , please let me know at
techienjoy at yahoo . com