public class ImprovedAdder extends JFrame
1:
2: import javax.swing.*;
3: import java.awt.*;
4: import java.awt.event.*;
5:
6: /**
7: GUI for totaling a series of numbers. If the user
8: enters a number in an incorrect format, such as
9: 2,000 with a comma, then an error message is generated
10: and the user can restart the computation.
11: */
12: public class ImprovedAdder extends JFrame
13: implements ActionListener
14: {
15: public static final int WIDTH = 400;
16: public static final int HEIGHT = 200;
17:
18: private JTextField inputOutputField;
19: private double sum = 0;
20:
21: public static void main(String[] args)
22: {
23: ImprovedAdder guiAdder = new ImprovedAdder( );
24: guiAdder.setVisible(true);
25: }
26:
27: public ImprovedAdder( )
28: {
29: setTitle("Adding Machine");
30: addWindowListener(new WindowDestroyer( ));
31: setSize(WIDTH, HEIGHT);
32: Container contentPane = getContentPane( );
33: contentPane.setLayout(new BorderLayout( ));
34:
35: JPanel buttonPanel = new JPanel( );
36: buttonPanel.setBackground(Color.GRAY);
37: buttonPanel.setLayout(new FlowLayout( ));
38: JButton addButton = new JButton("Add");
39: addButton.addActionListener(this);
40: buttonPanel.add(addButton);
41: JButton resetButton = new JButton("Reset");
42: resetButton.addActionListener(this);
43: buttonPanel.add(resetButton);
44: contentPane.add(buttonPanel, BorderLayout.SOUTH);
45:
46: JPanel textPanel = new JPanel( );
47: textPanel.setBackground(Color.BLUE);
48: textPanel.setLayout(new FlowLayout( ));
49:
50: inputOutputField = new JTextField("Numbers go here.", 30);
51: inputOutputField.setBackground(Color.WHITE);
52: textPanel.add(inputOutputField);
53: contentPane.add(textPanel, BorderLayout.CENTER);
54: }
55:
56: public void actionPerformed(ActionEvent e)
57: {
58: try
59: {
60: tryingCorrectNumberFormats(e);
61: }
62: catch (NumberFormatException e2)
63: {
64: inputOutputField.setText("Error: Reenter Number.");
65: }
66: }
67:
68: //This method can throw NumberFormatExceptions.
69: public void tryingCorrectNumberFormats(ActionEvent e)
70: {
71: if (e.getActionCommand( ).equals("Add"))
72: {
73: sum = sum +
74: stringToDouble(inputOutputField.getText( ));
75: inputOutputField.setText(Double.toString(sum));
76: }
77: else if (e.getActionCommand( ).equals("Reset"))
78: {
79: sum = 0;
80: inputOutputField.setText("0.0");
81: }
82: else
83: inputOutputField.setText("Error in adder code.");
84: }
85:
86: //This method can throw NumberFormatExceptions.
87: private static double stringToDouble(String stringObject)
88: {
89: return Double.parseDouble(stringObject.trim( ));
90: }
91: }
92:
93:
94: