Java Reference
In-Depth Information
Event-Handling Methods
When you associate an interface with a class, the class must handle all the methods con-
tained in the interface.
In the case of event listeners, each of the methods is called automatically by the window-
ing system when the corresponding user event takes place.
The ActionListener interface has only one method: actionPerformed() . All classes
that implement ActionListener must have a method with the following structure:
public void actionPerformed(ActionEvent event) {
// handle event here
}
If only one component in your program's graphical user interface has a listener for action
events, you will know that this actionPerformed() method only is called in response to
an event generated by that component.
If more than one component has an action event listener, you must use the ActionEvent
object to figure out which component was used and act accordingly in your program.
This object can be used to discover details about the component that generated the event.
ActionEvent and all other event objects are part of the java.awt.event package and
subclasses of the EventObject class.
Every event-handling method is sent an event object of some kind. The object's
getSource() method can be used to determine the component that sent the event, as in
the following example:
public void actionPerformed(ActionEvent event) {
Object source = evt.getSource();
}
The object returned by the getSource() method can be compared with components by
using the == operator. The following statements can be used within the body of an
actionPerformed() method to handle user clicks on buttons named quitButton and
sortRecords :
if (source == quitButton) {
quitProgram();
}
if (source == sortRecords) {
sortRecords();
}
Search WWH ::




Custom Search