ptg7068951
Handling User Events 203
Each listener has different methods that are called to receive their events.
The ActionListenerinterface sends events to a method called
actionPerformed(). The following is a short example of an
actionPerformed()method:
public voidactionPerformed(ActionEvent event) {
// method goes here
}
All action events sent in the program go to this method. If only one com-
ponent in a program can possibly send action events, you can put state-
ments in this method to handle the event. If more than one component can
send these events, you need to check the object sent to the method.
An ActionEventobject is sent to the actionPerformed()method. Several
different classes of objects represent the user events that can be sent in a
program. These classes have methods to determine which component
caused the event to happen. In the actionPerformed()method, if the
ActionEventobject is named event, you can identify the component with
the following statement:
String cmd = event.getActionCommand();
The getActionCommand()method sends back a string. If the component is
a button, the string is the label on the button. If it’s a text field, the string is
the text entered in the field. The getSource()method sends back the
object that caused the event.
You could use the following actionPerformed()methodto receive events
from three components: a JButtonobject called start, a JTextFieldcalled
speed, and another JTextFieldcalled viscosity:
public voidactionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == speed) {
// speed field caused event
} else if(source == viscosity) {
// viscosity caused event
} else{
// start caused event
}
}
You can call the getSource()method on all user events to identify the spe-
cific object that caused the event.