Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^388) | Event-Driven Input and Output
classButtonHandler implementsActionListener
{
public voidactionPerformed(ActionEvent event) // Event handler method
{
// Body of button event handler method goes here
}
} // End of ButtonHandler
There are only two major differences between this and the other classes that we’ve declared:
 The class heading includes the clause implementsActionListener.
 The heading of the actionPerformedmethod must have a signature that matches
the example.
In Chapter 7 we saw an implementsclause when we output objects to a file and read them
back in. There, we used the clause implementsSerializablein our class headings.Serializable
is another interface that is defined in the Java library. Unlike ActionListener,however,the
Serializableinterface does not require that we implement any methods. Merely including
the implementsSerializableclause in the class heading is sufficient to tell Java that objects
of that class should be prepared for input and output. Now, let’s take a closer look at our im-
plementation of ActionListener.
No modifiers appear in front of the heading for the class ButtonHandlerin our example.
You must decide which ones are appropriate for each situation. When the class is defined
in the application class itself, you might use privateand static. If the class is defined as
part of a package that you import, it could be public. When you are handling all events from
a class of event sources, for example, and all of the buttons will be registered with this one
handler, then it should be static. If you plan to instantiate different handlers for use by dif-
ferent event sources, however, then the modifier should not be static.
Just as we get to choose the name of any other class, so we also get to choose the name
(ButtonHandler) of the class that implements ActionListener. The interface specifies that
actionPerformedhas one parameter of the class ActionEvent(a predefined class that represents
a source event). We can choose any name that we wish for the parameter; here we simply
called it event.
The fact that our new class implementsthe ActionListenerinterface means that we can
pass a ButtonHandlerobject to any method that specifies a parameter of type ActionListener
(such as the addActionListenermethod). A class that implements an interface can be used in
place of the interface that it implements.
Let’s look at how this class definition is written within an application. We provide a
skeleton of an application that includes just the essential parts of the two classes.
// Import declarations go here
public classButtonDemo // Application class heading
{
// Start of ButtonHandler class
private static classButtonHandler implementsActionListener

Free download pdf