Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event raise-handling in Java

Tags:

java

events

How to raise custom events and handle in Java. Some links will be helpful.

Thanks.

like image 805
bdhar Avatar asked Jul 30 '09 07:07

bdhar


2 Answers

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
  }
});
like image 90
Pavel Minaev Avatar answered Nov 15 '22 07:11

Pavel Minaev


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

like image 34
Bob Avatar answered Nov 15 '22 06:11

Bob