Java Reference
In-Depth Information
LISTING 12.2
Continued
10: JTextField sum = new JTextField(“0”, 5);
11:
12: public Calculator() {
13: super(“Add Two Numbers”);
14: setSize(350, 90);
15: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16: FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
17: setLayout(flow);
18: // add listeners
19: value1.addFocusListener(this);
20: value2.addFocusListener(this);
21: // set up sum field
22: sum.setEditable(false);
23: // add components
24: add(value1);
25: add(plus);
26: add(value2);
27: add(equals);
28: add(sum);
29: setVisible(true);
30: }
31:
32: public void focusGained(FocusEvent event) {
33: try {
34: float total = Float.parseFloat(value1.getText()) +
35: Float.parseFloat(value2.getText());
36: sum.setText(“” + total);
37: } catch (NumberFormatException nfe) {
38: value1.setText(“0”);
39: value2.setText(“0”);
40: sum.setText(“0”);
41: }
42: }
43:
44: public void focusLost(FocusEvent event) {
45: focusGained(event);
46: }
47:
48: public static void main(String[] arguments) {
49: Calculator frame = new Calculator();
50: }
51: }
12
Figure 12.2 shows the application.
In the Calculator application, focus listeners are added to the first two text fields,
value1 and value2 , and the class implements the FocusListener interface.
 
Search WWH ::




Custom Search