Give a brief explanation about action events and listeners?

Components such as the Button and JButtonfire off ActionEvents to indicate some kind of component-defined action. For example, the Button fires off an ActionEvent whenever the user presses it. The entire point of an event is to inform a listener that something has happened to a component in the GUI. An event includes all of the information that a listener needs to figure out what happened and to whom it happened (the what and who of the event). An event must give enough information to fully describe itself. That way, a listener can figure out what exactly happened and respond in a meaningful way.

The ActionEvent includes methods for learning the action's command string, modifiers, and identification string. The getActionCommand() method returns the command string that indicates the event's intended action, such as print or copy (the what). The getSource() method returns the object that generates the event (the who).In order to receive an ActionEvent, a listener must implement the ActionListenerinterface and register itself with the component. Furthermore, a component must keep track of its listeners in order to notify them of an event.

By using the ActionEvent example as a model, we can easily see the pieces necessary for a component to generate an event and a listener to listen for an event. At a high level, there are three pieces:

  1. The component
  2. The event class
  3. The listener interface  

    The component

    Components generate events. An event is a component's way of letting a listener know that something has happened. Therefore, a component must provide a mechanism to register and deregister event listeners. The component must also track its listeners and pass on the events to those listeners.The mechanics of registration/deregistration and tracking are left to the individual component. However, a component will normally have  addXXXListener and removeXXXListener for each type of event that it generates. Internally, the component may store a listener however it chooses; usually, however, components store listeners in a java.util.Vector or javax.swing.event.EventListenerList. To fire off an event to its listeners, the component simply loops through its list of listeners and passes the event to each listener by calling the listener's event dispatch method.

    The event class

    The event holds all of the information necessary for a listener to figure out what happened. The information included is really event specific. Just think about the event carefully and design the event class to hold whatever information is necessary to fully describe the event to a listener. Events normally extend the java.awt.AWTEventevent class.

    The listener interface

    An event listener interface defines the methods used by a component to dispatch events. Each event type will have at least one corresponding dispatch method in a listener interface.

Posted on by