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 |
This program shows a frame with a text area that displays |
13 |
the growth of an investment. A second frame holds a text |
14 |
field to specify the interest rate. |
15 |
*/ |
16 |
public class TextAreaTest |
17 |
{ |
18 |
public static void main(String[] args) |
19 |
{ |
20 |
// the application adds interest to this bank account |
21 |
final BankAccount account = new BankAccount(INITIAL_BALANCE); |
22 |
// the text area for displaying the results |
23 |
final JTextArea textArea = new JTextArea(10, 30); |
24 |
textArea.setEditable(false); |
25 |
JScrollPane scrollPane = new JScrollPane(textArea); |
26 |
|
27 |
// construct the frame for displaying the text area |
28 |
JFrame frame = new JFrame(); |
29 |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
30 |
frame.setContentPane(scrollPane); |
31 |
frame.pack(); |
32 |
frame.show(); |
33 |
|
34 |
// the label and text field for entering the interest rate |
35 |
JLabel rateLabel = new JLabel("Interest Rate: "); |
36 |
|
37 |
final JTextField rateField = new JTextField(10); |
38 |
rateField.setText("" + DEFAULT_RATE); |
39 |
|
40 |
// the button to trigger the calculation |
41 |
JButton calculateButton = new JButton("Add Interest"); |
42 |
|
43 |
class CalculateListener implements ActionListener |
44 |
{ |
45 |
public void actionPerformed(ActionEvent event) |
46 |
{ |
47 |
double rate = Double.parseDouble( |
48 |
rateField.getText()); |
49 |
double interest = account.getBalance() |
50 |
* rate / 100; |
51 |
account.deposit(interest); |
52 |
textArea.append(account.getBalance() + "\n"); |
53 |
} |
54 |
} |
55 |
|
56 |
ActionListener listener = new CalculateListener(); |
57 |
calculateButton.addActionListener(listener); |
58 |
|
59 |
// the control panel that holds the input components |
60 |
JPanel controlPanel = new JPanel(); |
61 |
controlPanel.add(rateLabel); |
62 |
controlPanel.add(rateField); |
63 |
controlPanel.add(calculateButton); |
64 |
|
65 |
// the frame to hold the control panel |
66 |
JFrame controlFrame = new JFrame(); |
67 |
controlFrame.setContentPane(controlPanel); |
68 |
controlFrame.pack(); |
69 |
controlFrame.show(); |
70 |
} |
71 |
|
72 |
private static final double DEFAULT_RATE = 10; |
73 |
private static final double INITIAL_BALANCE = 1000; |
74 |
} |