The Java Event Delegation Model

Sources, Events, and Listeners

In the Java Event Delegation Model the publisher (source) notifies registered subscribers (listeners) when certain events occur.

There are many types of events and listeners in Java:

 

 

Action Events

Action events—also called semantic events—are fired by GUI controls such as buttons, text fields, and menu items when they are activated by the user.

For example, in the reactor console constructor, an IncAction listener is added to the list of listeners for the "inc" button and a DecAction listener is added to the list of listeners for the "dec" button (these are the only listeners):

incButton.addActionListener(new IncAction());
decButton.addActionListener(new DecAction());

IncAction and DecAction are declared as inner classes of the ReactorConsole class. This is commonly done because these classes are seldom reusable outside of a particular GUI, but also because inner class instances have access to the private variables of the outer class instance that creates them. Thus, our listeners can access the myReactor reference of the reactor console that creates them:

   class IncAction implements ActionListener {
      public void actionPerformed(ActionEvent a) {
         myReactor.inc(500);
      }
   }

   class DecAction implements ActionListener {
      public void actionPerformed(ActionEvent a) {
         myReactor.dec(50);
      }
   }

Notice that this is yet another example of the Publisher-Subscriber pattern. Components are publishers. They publish events. Listeners are subscribers. They must implement methods prescribed by appropriate listener interfaces and they must register with the components they listen to. When an event is fired, the appropriate methods of every registered listener is called.

Property Change Event

Components—reusable, replaceable modules—are called Java beans.

A bean has four types of properties: simple, indexed, bound, and constrained. Bound and constrained properties fire property change events when someone attempts to change their values. If an attempt is made to change a constrained property, an exception is thrown and the change fails if one of the listeners vetoes the change.