tags:

views:

218

answers:

3
+4  Q: 

Java events

How does the event creation and handling work in Java?

A: 

There's a tutorial on eveng handling here: http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

It's about Swing. If that doesn't work maybe you could be a bit more specific?

Phill Sacre
+6  A: 

The java event mechanism is actually an implementation of the Observer design pattern. I suggest you do alittle reading on the observer pattern, this will give you a lot of insight on how the event mechanism in Java works.

See observer pattern on Wikipedia

nkr1pt
+5  A: 

Generally events are handled by registering a callback function with the class that would raise the event. When the event occurs, that class will call the callback function.

You will find a lot of examples from swing. Here is a non-swing example from a chat application i made some time back

This was a library that would let the developer embed chat capabilities to their apps. The ChatClient class has a member of IMessageListener type

IMessageListener listener;

Afer creating the object for the ChatClient class, the user will call setListener on the object. (Could be addListerer for multiple listeners)

public void setListener(IMessageListener listener) {
 this.listener = listener;
}

And in the library method when a message is recieved, i would call the getMessage method on that listener object

This was a basic example. More sophisticated libraries would use more complex methods, like implementing event queues, threading, concurrency etc.

Edit: And Yes. this is the observer pattern indeed

Midhat