There are no first-class events in Java. All event processing is performed using interfaces and a listener template. 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) {
Pavel minaev
source share