1 import java.awt.event.ActionEvent;
2 import java.awt.event.ActionListener;
3 import javax.swing.JButton;
4 import javax.swing.JFrame;
5 import javax.swing.JLabel;
6 import javax.swing.JPanel;
7 import javax.swing.JScrollPane;
8 import javax.swing.JTextArea;
9 import javax.swing.JTextField;
10
11 /**
12 A frame that shows the growth of an investment with variable interest.
13 */
14 public class InvestmentFrame extends JFrame
15 {
16 private static final int FRAME_WIDTH = 400;
17 private static final int FRAME_HEIGHT = 250;
18
19 private static final int AREA_ROWS = 10;
20 private static final int AREA_COLUMNS = 30;
21 private static final double DEFAULT_RATE = 5;
22 private static final double INITIAL_BALANCE = 1000;
23
24 private JLabel rateLabel;
25 private JTextField rateField;
26 private JButton button;
27 private JTextArea resultArea;
28 private JPanel panel;
29 private BankAccount account;
30
31 public InvestmentFrame()
32 {
33 account = new BankAccount(INITIAL_BALANCE);
34 resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
35 resultArea.setEditable(false);
36
37 // Use helper methods
38 createTextField();
39 createButton();
40 createPanel();
41
42 setSize(FRAME_WIDTH, FRAME_HEIGHT);
43 }
44
45 private void createTextField()
46 {
47 rateLabel = new JLabel("Interest Rate: ");
48
49 final int FIELD_WIDTH = 10;
50 rateField = new JTextField(FIELD_WIDTH);
51 rateField.setText("" + DEFAULT_RATE);
52 }
53
54 private void createButton()
55 {
56 button = new JButton("Add Interest");
57
58 class AddInterestListener implements ActionListener
59 {
60 public void actionPerformed(ActionEvent event)
61 {
62 double rate = Double.parseDouble(rateField.getText());
63 double interest = account.getBalance() * rate / 100;
64 account.deposit(interest);
65 resultArea.append(account.getBalance() + "\n");
66 }
67 }
68
69 ActionListener listener = new AddInterestListener();
70 button.addActionListener(listener);
71 }
72
73 private void createPanel()
74 {
75 panel = new JPanel();
76 panel.add(rateLabel);
77 panel.add(rateField);
78 panel.add(button);
79 JScrollPane scrollPane = new JScrollPane(resultArea);
80 panel.add(scrollPane);
81 add(panel);
82 }
83 }