public class ImprovedAdder extends JFrame
1:
2: import javax.swing.JButton;
3: import javax.swing.JFrame;
4: import javax.swing.JPanel;
5: import javax.swing.JTextField;
6: import java.awt.Color;
7: import java.awt.Container;
8: import java.awt.BorderLayout;
9: import java.awt.FlowLayout;
10: import java.awt.event.ActionEvent;
11: import java.awt.event.ActionListener;
12: /**
13: GUI for adding a series of numbers. If the user
14: enters a number in an incorrect format, such as
15: 2,000 with a comma, an error message is generated
16: and the user can restart the computation.
17: */
18: public class ImprovedAdder extends JFrame
19: implements ActionListener
20: {
21: public static final int WIDTH = 400;
22: public static final int HEIGHT = 200;
23:
24: private JTextField inOutField;
25: private double sum = 0;
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: inOutField = new JTextField("Numbers go here.", 30);
51: inOutField.setBackground(Color.WHITE);
52: textPanel.add(inOutField);
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: inOutField.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 + stringToDouble(inOutField.getText( ));
74: inOutField.setText(Double.toString(sum));
75: }
76: else if (e.getActionCommand( ).equals("Reset"))
77: {
78: sum = 0;
79: inOutField.setText("0.0");
80: }
81: else
82: inOutField.setText("Error in adder code.");
83: }
84:
85: //This method can throw NumberFormatExceptions.
86: private static double stringToDouble(String stringObject)
87: {
88: return Double.parseDouble(stringObject.trim( ));
89: }
90:
91: public static void main(String[] args)
92: {
93: ImprovedAdder guiAdder = new ImprovedAdder( );
94: guiAdder.setVisible(true);
95: }
96: }
97:
98:
99: