Java Reference
In-Depth Information
The second line says that buttonEar is registered as a listener to endButton , which
means buttonEar will receive all events fired by endButton .
Different kinds of components require different kinds of listener classes to handle
the events they fire. A button fires events known as action events , which are handled
by listeners known as action listeners .
An action listener is an object whose class implements the ActionListener
interface. For example, the class EndingListener in Display 17.2 implements the
ActionListener interface. The ActionListener interface has only one method
heading that must be implemented, namely the following:
action event
Action
Listener
action
Performed
public void actionPerformed(ActionEvent e)
In the class EndingListener in Display 17.2 , the actionPerformed method is
defined as follows:
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
If the user clicks the button endButton , it sends an action event to the action listener
for that button. But buttonEar is the action listener for the button endButton , so the
action event goes to buttonEar . When an action listener receives an action event, the
event is automatically passed as an argument to the method actionPerformed and
the method actionPerformed is invoked. If the event is called e , then the following
invocation takes place in response to endButton firing e :
buttonEar.actionPerformed(e);
In this case, the parameter e is ignored by the method actionPerformed . The method
actionPerformed simply invokes System.exit and thereby ends the program. So, if
the user clicks endButton (the one labeled "Click to end program." ), the net effect
is to end the program and so the window goes away.
Note that you never write any code that says
buttonEar.actionPerformed(e);
This action does happen, but the code for this is embedded in some class definition
inside the Swing and/or AWT libraries. Somewhere the code says something like
bla.actionPerformed(e);
and somehow buttonEar gets plugged in for the parameter bla and this invocation
of actionPerformed is executed. But, all this is done for you. All you do is define the
method actionPerformed and register buttonEar as a listener for endButton .
Note that the method actionPerformed must have a parameter of type
ActionEvent , even if your definition of actionPerformed does not use this parameter.
This is because the invocations of actionPerformed were already programmed for
you and so must allow the possibility of using the ActionEvent parameter e . As you
will see, in other Swing GUIs the method actionPerformed does often use the event
e to determine which button was clicked. This first example is a special, simple case
 
Search WWH ::




Custom Search