1 import java.awt.event.ActionEvent;
2 import java.awt.event.ActionListener;
3 import javax.swing.JButton;
4 import javax.swing.JFrame;
5
6 /**
7 This program demonstrates how an action listener can access
8 a variable from a surrounding block.
9 */
10 public class InvestmentViewer1
11 {
12 private static final int FRAME_WIDTH = 120;
13 private static final int FRAME_HEIGHT = 60;
14
15 private static final double INTEREST_RATE = 10;
16 private static final double INITIAL_BALANCE = 1000;
17
18 public static void main(String[] args)
19 {
20 JFrame frame = new JFrame();
21
22 // The button to trigger the calculation
23 JButton button = new JButton("Add Interest");
24 frame.add(button);
25
26 // The application adds interest to this bank account
27 final BankAccount account = new BankAccount(INITIAL_BALANCE);
28
29 class AddInterestListener implements ActionListener
30 {
31 public void actionPerformed(ActionEvent event)
32 {
33 // The listener method accesses the account variable
34 // from the surrounding block
35 double interest = account.getBalance() * INTEREST_RATE / 100;
36 account.deposit(interest);
37 System.out.println("balance: " + account.getBalance());
38 }
39 }
40
41 ActionListener listener = new AddInterestListener();
42 button.addActionListener(listener);
43
44 frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
45 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
46 frame.setVisible(true);
47 }
48 }