How do events work in Java Swing?

How does event creation and handling work in Java Swing?

+6
java events swing
source share
3 answers

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

See Wikipedia Observer Pattern

+10
source share

Typically, events are handled by registering a callback function with the class that raises the event. When an event occurs, this class will call the callback function.

You will find many examples of swings. Here is an example of a non-rotation from a chat application that I did some time ago

It was a library that would allow the developer to embed chat features in their applications. The ChatClient class has a member of type IMessageListener

IMessageListener listener; 

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

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

And in the library method, when the message is received, I would call the getMessage method for this listener object

This was a basic example. More complex libraries will use more complex methods, such as implementing event queues, threads, concurrency, etc.

Edit: Yes. it really is an observer pattern.

+6
source share

There is a tutorial on working with eveng here: http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

This is about Swing. If that doesn't work, maybe you can be more specific?

0
source share

All Articles