Java Reference
In-Depth Information
Second, it must define the methods that will be invoked when the event is sent to
the listener. Note that these methods will be defined by you, but in normal circum-
stances, you will never write an invocation of these methods. The invocations will
take place automatically.
The following lines from Display 17.2 create an EndingListener object named
buttonEar and register buttonEar as a listener to receive events from the button
named endButton :
addAction-
Listener
EndingListener buttonEar = new EndingListener();
endButton.addActionListener(buttonEar);
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 inter-
face. For example, the class EndingListener in Display 17.2 implements the Action-
Listener interface. The ActionListener interface has only one method heading that
must be implemented, namely the following:
action event
action
listener
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 , that sends an action event to the action lis-
tener 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 actionPer-
formed 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);
Search WWH ::




Custom Search