How to raise custom events and handle in Java. Some links will be helpful.
Thanks.
There are no first-class events in Java. All event handling is done using interfaces and listener pattern. For example:
// Roughly analogous to .NET EventArgs
class ClickEvent extends EventObject {
public ClickEvent(Object source) {
super(source);
}
}
// Roughly analogous to .NET delegate
interface ClickListener extends EventListener {
void clicked(ClickEvent e);
}
class Button {
// Two methods and field roughly analogous to .NET event with explicit add and remove accessors
// Listener list is typically reused between several events
private EventListenerList listenerList = new EventListenerList();
void addClickListener(ClickListener l) {
clickListenerList.add(ClickListener.class, l)
}
void removeClickListener(ClickListener l) {
clickListenerList.remove(ClickListener.class, l)
}
// Roughly analogous to .net OnEvent protected virtual method pattern -
// call this method to raise the event
protected void fireClicked(ClickEvent e) {
ClickListener[] ls = listenerList.getListeners(ClickEvent.class);
for (ClickListener l : ls) {
l.clicked(e);
}
}
}
Client code typically uses anonymous inner classes to register handlers:
Button b = new Button();
b.addClickListener(new ClickListener() {
public void clicked(ClickEvent e) {
// handle event
}
});
Java lacks intrinsic event handling, but there are libraries to help you accomplish this. Check out javaEventing, http://code.google.com/p/javaeventing/ It works much as in C# where you first define your events, and then register event listeners. You trigger events using EventManager.triggerEvent(..someEvent). It allows you to provide custom conditions and payloads with your events as well.
bob
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With