Java Reference
In-Depth Information
As far as the compiler is concerned, this class has two methods:
public void actionPerformed(ActionEvent event)
public void actionPerformed()
The first method is undefined. The compiler will complain that the method is
missing. You have to read the error message carefully and pay attention to the
parameter and return types to find your error.
9.7 Using Inner Classes for Listeners
In the preceding section, you saw how the code that is executed when a button is
clicked is placed into a listener class. It is common to implement listener classes as
inner classes like this:
JButton button = new JButton(". . .");
// This inner class is declared in the same method as the button variable
class MyListener implements ActionListener
{
. . .
};
ActionListener listener = new MyListener();
button.addActionListener(listener);
There are two reasons for this arrangement. First, it places the trivial listener class
exactly where it is needed, without cluttering up the remainder of the project.
Moreover, inner classes have a very attractive feature: Their methods can access
variables that are defined in surrounding blocks. In this regard, method definitions of
inner classes behave similarly to nested blocks.
411
412
Recall that a block is a statement group enclosed by braces. If a block is nested inside
another, the inner block has access to all variables from the surrounding block:
{ // Surrounding block
BankAccount account = new BankAccount();
if (. . .)
{ // Inner block
. . .
// OK to access variable from surrounding block
Search WWH ::




Custom Search