Programming and Problem Solving with Java

(やまだぃちぅ) #1
8.3 Event Handling | 389

{

public voidactionPerformed(ActionEvent event) // Event handler method
{
// Body of button event handler method goes here
}
} // End of ButtonHandler class

// More declarations for the application (ButtonDemo)

public static voidmain(String[] args) // main, just as usual
{
... // Body of main starts here
JButton done; // Declare a button variable
ButtonHandler buttonAction; // Button listener variable
... // Declarations, set up frame, etc.
done = new JButton("Done"); // Instantiate a button
buttonAction = new ButtonHandler(); // Instantiate the listener
done.addActionListener(buttonAction); // Register the event listener
outPane.add(done); // Add the button to the pane
... // Remainder of application
}
}


As you can see, this application class is just like those we’ve written previously, except that
it contains another class with one method inside of it. We could also declare the ButtonHandler
class separately and import it into our application.
Because addActionListeneris an instance method associated with done, this particular
event listener is registered with the event that is generated by the button. We can register
an event listener with multiple sources (different buttons) so that one handler method re-
sponds to all of those sources. Alternatively, we can register each source with a different
handler. We explore both of these approaches later in this chapter.
Although we use the identifier “ButtonHandler” for the class, it is actually a listener class.
Because the listener contains the method that handles the event, we use the linguistic short-
cut of calling it a button handler rather than calling it “the listener that contains the method
that handles the event.” All we have to do to complete the ButtonHandlerclass definition is
fill in the body of the actionPerformedmethod with statements to be executed when the
event fires. Those statements might be, for example,


dataPane.add(new JLabel("Some new label text")); // Add a new label
dataLabel.setText("Replacement text"); // Change an existing label


From the preceding code, we can see that we need to take three steps to register the lis-
tener with the event source:


1.Declare a variable of the listener class (for example,ButtonHandler).
2.Instantiate an object of the listener class.
Free download pdf