Java Reference
In-Depth Information
This action does happen, but the code for this is embedded in some class definition
inside the Swing and/or AWT libraries. Somewhere the code says something like
bla.actionPerformed(e);
and somehow buttonEar gets plugged in for the parameter bla and this invocation of
actionPerformed is executed. But, all this is done for you. All you do is define the
method actionPerformed and register buttonEar as a listener for endButton .
Note that the method actionPerformed must have a parameter of type ActionEvent ,
even if your definition of actionPerformed does not use this parameter. This is because
the invocations of actionPerformed were already programmed for you and so must
allow the possibility of using the ActionEvent parameter e . As you will see, in other
Swing GUIs the method actionPerformed does often use the event e to determine
which button was clicked. This first example is a special, simple case because there is only
one button. Later in this chapter we will say more about defining the actionPerformed
method in more complicated situations. 3 4 5
PITFALL: Changing the Heading for actionPerformed
When you define the method actionPerformed in an action listener, you are imple-
menting the method heading for actionPerformed that is specified in the Action-
Listener interface. Thus, the header for the method actionPerformed is determined
for you, and you cannot change the heading. It must have exactly one parameter, and
that parameter must be of type ActionEvent , as in the following:
public void actionPerformed(ActionEvent e)
If you change the type of the parameter or if you add (or subtract) a parameter, you will not
have given a correct definition of an action listener. 4 The only thing you can change is the
name of the parameter e , since it is just a placeholder. So the following change is acceptable:
public void actionPerformed(ActionEvent theEvent)
Of course, if you make this change, then inside the body of the method actionPerformed ,
you will use the identifier theEvent in place of the identifier e .
You also cannot add a throws clause to the method actionPerformed . 5 If a checked
exception is thrown in the definition of actionPerformed , then it must be caught in
the method actionPerformed . (Recall that a checked exception is one that must be
either caught in a catch block or declared in a throws clause.)
3
4 Although it would be rather questionable style, you can overload the method named actionPerformed
so that you have multiple versions of the method actionPerformed , each with a different parameter list.
But only the version of actionPerformed shown above has anything to do with making a class into an
action listener.
5 If you have not yet covered exception handling (Chapter 9), you can safely ignore this paragraph.
Search WWH ::




Custom Search