8.7 Reading Data in an Event Handler | 401
After the user enters a string and clicks the copy button, the frame appears as follows:
When the user closes the window, the program removes the frame from the screen and
quits. But what happens if the user doesn’t close the window? What if the user types some
more data and clicks the button again? The button fires another event, which dutifully calls
the event handler again, and the output label is updated with the new input value. The user
can keep entering new data values until he or she closes the window. We’ve created an event
loop! In some applications, this event loop would be useful. For this problem, however, our
intent is to allow the user to enter just one value.
How can we prevent the user from entering a second value? We can remove the button
from the pane so that it can’t be clicked again. A Containerobject supports a removemethod
that allows us to delete items that we’ve previously inserted with add. We can write a second
line in our event handler that calls this method for dataPane, passing it the button copy:
dataPane.remove(copy);
Notice, however, that dataPaneand copyare declared locally within main. If we want them
to be accessible to both mainand the event handler, then they must become class fields. Here
is the revised section of the class member declarations:
private staticJLabel outputLabel; // Label for output
private staticJTextField inputField; // Input field
private staticContainer dataPane; // Content pane
private staticJButton copy; // Copy button
Now, as soon as the user clicks the “Copy” button, the button disappears. At the same time,
the input string appears in the output label. The only event that the user can then generate
is closing the window.
Our example has demonstrated the input of a string. Just as with System.inand file in-
put,Stringis the only form of input that Java supports with a field. We must use one of the
parsemethods if we wish to input a numeric value. For example:
amount = Double.parseDouble(dataField.getText());
Now, let’s put together what we’ve seen thus far in a Case Study.