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 using a text area.
14 */
15 public class InvestmentFrame3 extends JFrame
16 {
17 private static final int FRAME_WIDTH = 400;
18 private static final int FRAME_HEIGHT = 250;
19
20 private static final int AREA_ROWS = 10;
21 private static final int AREA_COLUMNS = 30;
22
23 private static final double DEFAULT_RATE = 5;
24 private static final double INITIAL_BALANCE = 1000;
25
26 private JLabel rateLabel;
27 private JTextField rateField;
28 private JButton button;
29 private JTextArea resultArea;
30 private double balance;
31
32 public InvestmentFrame3()
33 {
34 balance = INITIAL_BALANCE;
35 resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
36 resultArea.setText(balance + "\n");
37 resultArea.setEditable(false);
38
39 createTextField();
40 createButton();
41 createPanel();
42
43 setSize(FRAME_WIDTH, FRAME_HEIGHT);
44 }
45
46 private void createTextField()
47 {
48 rateLabel = new JLabel("Interest Rate: ");
49
50 final int FIELD_WIDTH = 10;
51 rateField = new JTextField(FIELD_WIDTH);
52 rateField.setText("" + DEFAULT_RATE);
53 }
54
55 class AddInterestListener implements ActionListener
56 {
57 public void actionPerformed(ActionEvent event)
58 {
59 double rate = Double.parseDouble(rateField.getText());
60 double interest = balance * rate / 100;
61 balance = balance + interest;
62 resultArea.append(balance + "\n");
63 }
64 }
65
66 private void createButton()
67 {
68 button = new JButton("Add Interest");
69
70 ActionListener listener = new AddInterestListener();
71 button.addActionListener(listener);
72 }
73
74 private void createPanel()
75 {
76 JPanel panel = new JPanel();
77 panel.add(rateLabel);
78 panel.add(rateField);
79 panel.add(button);
80 JScrollPane scrollPane = new JScrollPane(resultArea);
81 panel.add(scrollPane);
82 add(panel);
83 }
84 }