Source of Adder.java


  1: import javax.swing.JButton;
  2: import javax.swing.JFrame;
  3: import javax.swing.JPanel;
  4: import javax.swing.JTextField;
  5: import java.awt.Color;
  6: import java.awt.Container;
  7: import java.awt.BorderLayout;
  8: import java.awt.FlowLayout;
  9: import java.awt.event.ActionEvent;
 10: import java.awt.event.ActionListener;
 11: 
 12: /**
 13:  GUI for totaling a series of numbers.
 14: */
 15: public class Adder extends JFrame implements ActionListener
 16: {
 17:     public static final int WIDTH = 400;
 18:     public static final int HEIGHT = 200;
 19: 
 20:     private JTextField inOutField;
 21:     private double sum = 0;
 22: 
 23:     public Adder( )
 24:     {
 25:         setTitle("Adding Machine");
 26:         addWindowListener(new WindowDestroyer( ));
 27:         setSize(WIDTH, HEIGHT);
 28:         Container contentPane = getContentPane( );
 29:         contentPane.setLayout(new BorderLayout( ));
 30: 
 31:         JPanel buttonPanel = new JPanel( );
 32:         buttonPanel.setBackground(Color.GRAY);
 33:         buttonPanel.setLayout(new FlowLayout( ));
 34:                 
 35:         JButton addButton = new JButton("Add");
 36:         addButton.addActionListener(this);
 37:         buttonPanel.add(addButton);
 38:                 
 39:         JButton resetButton = new JButton("Reset");
 40:         resetButton.addActionListener(this);
 41:         buttonPanel.add(resetButton);
 42:                 
 43:         contentPane.add(buttonPanel, BorderLayout.SOUTH);
 44: 
 45:         JPanel textPanel = new JPanel( );
 46:         textPanel.setBackground(Color.BLUE);
 47:         textPanel.setLayout(new FlowLayout( ));
 48: 
 49:         inOutField = new JTextField("Numbers go here.", 30);
 50:         inOutField.setBackground(Color.WHITE);
 51:         textPanel.add(inOutField);
 52:         contentPane.add(textPanel, BorderLayout.CENTER);
 53:     }
 54: 
 55:     public void actionPerformed(ActionEvent e)
 56:     {
 57:         if (e.getActionCommand( ).equals("Add"))
 58:         {
 59:             sum = sum + stringToDouble(inOutField.getText( ));
 60:             inOutField.setText(Double.toString(sum));
 61:         }
 62:         else if (e.getActionCommand( ).equals("Reset"))
 63:         {
 64:             sum = 0;
 65:             inOutField.setText("0.0");
 66:         }
 67:         else
 68:             inOutField.setText("Error in adder code.");
 69:     }
 70: 
 71:     private static double stringToDouble(String stringObject)
 72:     {
 73:         return Double.parseDouble(stringObject.trim( ));
 74:     }
 75: 
 76:     public static void main(String[] args)
 77:     {
 78:         Adder guiAdder = new Adder( );
 79:         guiAdder.setVisible(true);
 80:     }
 81: }