1 import java.awt.BorderLayout;
2 import java.awt.GridLayout;
3 import java.awt.event.ActionListener;
4 import java.awt.event.ActionEvent;
5 import javax.swing.JButton;
6 import javax.swing.JFrame;
7 import javax.swing.JPanel;
8 import javax.swing.JLabel;
9
10 /**
11 This frame contains a panel that displays buttons
12 for a calculator and a panel with a text fields to
13 specify the result of calculation. The operator
14 buttons don't do anything--see Worked Example 1
15 for a working calculator.
16 */
17 public class CalculatorFrame extends JFrame
18 {
19 private JLabel display;
20
21 private static final int FRAME_WIDTH = 300;
22 private static final int FRAME_HEIGHT = 300;
23
24 public CalculatorFrame()
25 {
26 display = new JLabel("0");
27 add(display, BorderLayout.NORTH);
28 createButtonPanel();
29 setSize(FRAME_WIDTH, FRAME_HEIGHT);
30 }
31
32 /**
33 Creates the button panel.
34 */
35 private void createButtonPanel()
36 {
37 JPanel buttonPanel = new JPanel();
38 buttonPanel.setLayout(new GridLayout(4, 4));
39
40 buttonPanel.add(makeDigitButton("7"));
41 buttonPanel.add(makeDigitButton("8"));
42 buttonPanel.add(makeDigitButton("9"));
43 buttonPanel.add(makeOperatorButton("/"));
44 buttonPanel.add(makeDigitButton("4"));
45 buttonPanel.add(makeDigitButton("5"));
46 buttonPanel.add(makeDigitButton("6"));
47 buttonPanel.add(makeOperatorButton("*"));
48 buttonPanel.add(makeDigitButton("1"));
49 buttonPanel.add(makeDigitButton("2"));
50 buttonPanel.add(makeDigitButton("3"));
51 buttonPanel.add(makeOperatorButton("-"));
52 buttonPanel.add(makeDigitButton("0"));
53 buttonPanel.add(makeDigitButton("."));
54 buttonPanel.add(makeOperatorButton("="));
55 buttonPanel.add(makeOperatorButton("+"));
56
57 add(buttonPanel, BorderLayout.CENTER);
58 }
59
60 class DigitButtonListener implements ActionListener
61 {
62 private String digit;
63
64 /**
65 Constructs a listener whose actionPerformed method adds a digit
66 to the display.
67 @param aDigit the digit to add
68 */
69 public DigitButtonListener(String aDigit)
70 {
71 digit = aDigit;
72 }
73
74 public void actionPerformed(ActionEvent event)
75 {
76 display.setText(display.getText() + digit);
77 }
78 }
79
80 /**
81 Makes a button representing a digit of a calculator.
82 @param digit the digit of the calculator
83 @return the button of the calculator
84 */
85 public JButton makeDigitButton(String digit)
86 {
87 JButton button = new JButton(digit);
88
89 ActionListener listener = new DigitButtonListener(digit);
90 button.addActionListener(listener);
91 return button;
92 }
93
94 /**
95 Makes a button representing an operator of a calculator.
96 @param op the operator of the calculator
97 @return the button of the calcalator
98 */
99 public JButton makeOperatorButton(String op)
100 {
101 JButton button = new JButton(op);
102 return button;
103 }
104 }