Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^410) | Event-Driven Input and Output
to the button to identify it. We access the string by calling the value-returning method
getActionCommandthat is associated with the parameter object.
For example, if the heading for actionPerformedis written
public voidactionPerformed(ActionEvent someButton)
then we obtain the string that identifies which button was clicked by using the following state-
ment (commandis a Stringvariable):
command = someButton.getActionCommand();
Within our declaration of the method, we use string comparisons and branches to per-
form the necessary action for the particular button. For example, we might extend the event
handler in our CopyStringclass as follows:
private static classButtonHandler implementsActionListener
{
public void actionPerformed(ActionEvent buttonEvent) // Event handler method
{
String command; // String to hold button name
command = buttonEvent.getActionCommand(); // Get the button's name
if (command.equals("Copy")) // When the name is "Copy"
outputLabel.setText(inputField.getText()); // Copy the field
else if(command.equals("Done")) // When the name is "Done"
{
dataFrame.dispose(); // Close the frame
System.exit(0); // Quit the program
}
else // Otherwise it's an error
outputLabel.setText("An unexpected event occurred.");
}
}
When the event source calls actionPerformed, the method gets the button’s name using
getActionCommand. It then uses an if-else-ifstructure to decide which button was clicked and
execute the appropriate statements. Although getActionCommandshould never return a name
other than "Copy"or "Done", we provide a branch for other names just to be safe. At some point
in the future, the program could be changed to add another button. If the new programmer
forgets to add a corresponding branch to handle that event, the program will display an er-
ror message instead of crashing.
T
E
A
M
F
L
Y
Team-Fly®

Free download pdf