8.7 Reading Data in an Event Handler | 399
pens after the code copies the string? The problem statement doesn’t answer this question.
We need a second event to indicate when the user has finished looking at the output. Such
an event could be generated by a second button, but instead we decide to do what we did in
our SimpleButtonexample and let the user close the window to end execution.
The event handler for the button simply copies the data from the input field to the out-
put label. For example:
fieldContents = inputField.getText();
outputLabel.setText(fieldContents);
We can even shorten these two lines to just one and eliminate the string variablefieldContents:
outputLabel.setText(inputField.getText());
This single line of code carries out the main action that we want to perform on the data. The
button event handler that contains it is written just as before, except that we insert this line
into the body of the method:
private static classButtonHandler implementsActionListener
{
public void actionPerformed(ActionEvent event) // Event handler method
{
outputLabel.setText(inputField.getText());
}
} // End of ButtonHandler
After this method executes, it returns control to the JVM. If the user then closes the window,
the application exits.
All that remains is to declare the appropriate variables, assign object addresses to them,
add them to the content pane, and show the frame on the screen. InSimpleButton, we saw that
the output label must be declared as a class field to make it accessible to bothmainand the event
handler. Do any of the other declarations here need to be declared outside ofmain? Yes. We want
to be able to initialize and add the data entry field inmain, and access it in the event handler,
so we also declare it at the class level. Here is the complete application, which we callCopyString:
//
// This application displays a frame with a data entry field and copies its
// contents to a label when the user clicks a button marked "Copy"
//
importjava.awt.; // Layout manager
importjava.awt.event.; // Event-handling classes
importjavax.swing.*; // User interface classes