Java Reference
In-Depth Information
Display 17.19
A Simple Calculator
(part 2 of 4)
44 JButton addButton =
new
JButton("+");
45 addButton.addActionListener(
this
);
46 buttonPanel.add(addButton);
47 JButton subtractButton =
new
JButton("—");
48 subtractButton.addActionListener(
this
);
49 buttonPanel.add(subtractButton);
50 JButton resetButton =
new
JButton("Reset");
51 resetButton.addActionListener(
this
);
52 buttonPanel.add(resetButton);
53 add(buttonPanel, BorderLayout.CENTER);
54 }
55
public void
actionPerformed(ActionEvent e)
56 {
57
try
58 {
59 assumingCorrectNumberFormats(e);
60 }
61
catch
(NumberFormatException e2)
62 {
63 ioField.setText("Error: Reenter Number.");
64 }
65 }
A
NumberFormatException
does not need to be declared
or caught in a catch block.
66
//Throws NumberFormatException.
67
public void
assumingCorrectNumberFormats(ActionEvent e)
68 {
69 String actionCommand = e.getActionCommand();
70
if
(actionCommand.equals("+"))
71 {
72 result = result + stringToDouble(ioField.getText());
73 ioField.setText(Double.toString(result));
74 }
75
else if
(actionCommand.equals("—"))
76 {
77 result = result − stringToDouble(ioField.getText());
78 ioField.setText(Double.toString(result));
79 }
80
else if
(actionCommand.equals("Reset"))
81 {
82 result = 0.0;
83 ioField.setText("0.0");
84 }
85
else
86 ioField.setText("Unexpected error.");
87 }
(continued)