Event Listeners

October 4th, 2008

The Java UI package, Swing, uses the concept of event listeners to connect UI components to the code that should be executed when those components are used.

In short, the idea of the event listener paradigm is that one object will notify one or more different objects when certain things occur (i.e. events).

From that description, there are two pieces necessary:

  • A class (known as an “event source”) needs to define the events it may trigger (another term is to “fire the event”). The event will likely carry data as to what caused the event and if any state has changed as a result (what information is carried is specific to the type of event). For instance, a button will fire an event when it is pressed. A text field will fire an event whenever its contents are changed. That class will also have the ability to track the listeners that should be notified when it fires an event.
  • Other classes are defined as a listener for those events. An interface is typically used to ensure the contract on the listener object. In other words, the listener interface will guarantee that the implementing class will have the necessary methods to handle the event. Once the event occurs, the event source will notify all of the listeners that the event has occurred.

Keep in mind that the listener instances are added to an event source instance. The same listener instance may be added to multiple event source instances.

The event listener paradigm isn’t strictly used by Swing. It is a common pattern that can be used in a number of different situations.

Below are a few helpful links specific to working with event listeners in Java Swing.

Comments are closed.