Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^409


With applications that input data from fields, the most common error is to try to as-
sign the field contents directly to an intor doublevariable. Remember that Java takes
only Stringvalues as input and that you must convert the input to any other type with
the appropriate parsemethod. Another common problem arises when the user enters a
number that causes integer overflow. When you want a field to input an integer value,
limit its size (through the constructor call) to nine characters. As noted earlier, we are
not yet ready to handle errors in which the user enters nonnumeric data into such a
field. Our application simply crashes with an error message if this error happens.

8.8 Handling Multiple Button Events


When we first discussed the handling of button events in a frame, we restricted our user in-
terface to a single button. In the preceding Case Study, we created a user interface containing
multiple buttons, but each button was registered with a different event handler instance. In
this section, we consider the handling of events from multiple buttons with a single handler.
When we instantiate a button with new, we pass a string as an argument to its constructor.
This string is used to label the button on the screen. However, it is also used to identify an
event from the button. For example, suppose we need a user interface with two buttons,
copyand done. We create one ButtonHandlerlistener object, and register it with both but-
tons as follows:


buttonAction = new ButtonHandler(); // Instantiate a ButtonHandler object,
// and assign its address to the variable
// buttonAction.
copy = new JButton("Copy"); // Instantiate a JButton object that is
// displayed with the word "Copy" and
// assign its address to the variable copy.
// The string also identifies it.
copy.addActionListener(buttonAction); // Register the button listener.
done = new JButton("Done"); // Instantiate a second JButton that
// displays the word "Done" inside it.
// Assign its address to the variable done.
// The string also identifies it.
done.addActionListener(buttonAction); // Register the button listener.


Figure 8.8 shows a frame with these buttons in it.
When the user clicks either of these buttons,actionPerformedis
called, just as we saw previously. How doesactionPerformeddecide
which button was clicked? Recall that when we write the heading for
the actionPerformed method, we include a parameter of type
ActionEvent. The event source passes an object to the method through
that parameter. That object has a field containing the string we gave Figure 8.8 Frame with Two Buttons

Free download pdf