Java Reference
In-Depth Information
because there is only one button. Later in this chapter, we will say more about defining
the actionPerformed method in more complicated situations.
PITFALL: Changing the Heading for actionPerformed
When you define the method actionPerformed in an action listener, you are
implementing the method heading for actionPerformed that is specified in the
ActionListener 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 , because 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 I f a
checked exception is thrown in the defi nition 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.)
TIP: Ending a Swing Program
A GUI program is normally based on a kind of infinite loop. There may not be a Java
loop statement in a GUI program, but nonetheless the GUI program need not ever
end. The windowing system normally stays on the screen until the user indicates that
it should go away (for example, by clicking the "Click to end program." button
in Display 17.2). If the user never asks the windowing system to go away, it will never
go away. When you write a Swing GUI program, you need to use System.exit to
end the program when the user (or something else) says it is time to do so. Unlike
the kinds of programs we saw before this chapter, a Swing program will not end after
it has executed all the code in the program. A Swing program does not end until it
executes a System.exit . (In some cases, the System.exit may be in some library
code and need not be explicitly given in your code.)
System.exit
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 here 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