tags:

views:

1522

answers:

4

Hi All,

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

Thanks.

+1  A: 

Java hasn't built-in support for delegates and events like C#. You would need to implement the Observer or Publish/Subscribe pattern yourself.

kgiannakakis
A: 

Java has no in-language support for events handling. But there's some classes that can help. You may look at java.awt.Event class; java.awt.event and java.beans packages. First package is a base for event handling in AWT and Swing GUI libraries. java.beans package contains supporting stuff for Java Beans specification, including property change events and bean context events.

Generally, event handling is implemented according to Observer or Publish/Subscribe patterns (as mentioned by kgiannakakis)

Rorick
+3  A: 

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 {
  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;

  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
  }
});
Pavel Minaev
Thanks! But how to raise the ClickEvent in code?-
bdhar
Call `fireClicked` method.
Pavel Minaev
A: 

The following linked helped me to understand.

http://www.javaworld.com/javaworld/javaqa/2002-03/01-qa-0315-happyevent.html

bdhar
Hey you can accept your own answer if it is more appropriate than any other answer
yesraaj
This is similar: http://www.exampledepot.com/egs/java.util/custevent.html