Using Inner Classes for Listeners
Implement simple 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);
This places the trivial listener class exactly where it is needed, without cluttering up the remainder of the project
Methods of an inner class can access local variables from surrounding blocks and fields from surrounding classes
Local variables that are accessed by an inner class method must be declared as final
Example: add interest to a bank account whenever a button is clicked:
JButton button = new JButton("Add Interest");
final BankAccount account = new BankAccount(INITIAL_BALANCE);
// This inner class is declared in the same method as the account
// and button variables.
class AddInterestListener implements ActionListener
{public void actionPerformed(ActionEvent event)
{
// The listener method accesses the account variable
// from the surrounding block
double interest = account.getBalance() * INTEREST_RATE / 100;
account.deposit(interest);
}};
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
Click here to see the example.
Why would an inner class method want to access a variable from a surrounding scope?
Answer:
Direct access is simpler than the alternative – passing
the variable as a parameter to a constructor or method.
If an inner class accesses a local variable from a surrounding scope, what special rule applies?
Answer: The local variable must be declared as final.