Source of AdderApplet.java


  1: 
  2: import javax.swing.JApplet;
  3: import javax.swing.JButton;
  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: public class AdderApplet extends JApplet 
 14:                          implements ActionListener
 15: {
 16:     private JTextField inputOutputField;
 17:     private double sum = 0;
 18: 
 19:     public void init( )
 20:     {
 21:         Container contentPane = getContentPane( );
 22:         contentPane.setLayout(new BorderLayout( ));
 23: 
 24:         JPanel buttonPanel = new JPanel( );
 25:         buttonPanel.setBackground(Color.GRAY);
 26:         buttonPanel.setLayout(new FlowLayout( ));
 27:                 
 28:         JButton addButton = new JButton("Add");
 29:         addButton.addActionListener(this);
 30:         buttonPanel.add(addButton);
 31:                 
 32:         JButton resetButton = new JButton("Reset");
 33:         resetButton.addActionListener(this);
 34:         buttonPanel.add(resetButton);
 35:                 
 36:         contentPane.add(buttonPanel, BorderLayout.SOUTH);
 37: 
 38:         JPanel textPanel = new JPanel( );
 39:         textPanel.setBackground(Color.BLUE);
 40:         textPanel.setLayout(new FlowLayout( ));
 41:                 
 42:         inputOutputField = 
 43:                        new JTextField("Numbers go here.", 30);
 44:         inputOutputField.setBackground(Color.WHITE);
 45:         textPanel.add(inputOutputField);
 46:                 
 47:         contentPane.add(textPanel, BorderLayout.CENTER);
 48:     }
 49: 
 50:     public void actionPerformed(ActionEvent e)
 51:     {
 52:         if (e.getActionCommand( ).equals("Add"))
 53:         {
 54:             sum = sum +
 55:                 stringToDouble(inputOutputField.getText( ));
 56:             inputOutputField.setText(Double.toString(sum));
 57:         }
 58:         else if (e.getActionCommand( ).equals("Reset"))
 59:         {
 60:             sum = 0;
 61:             inputOutputField.setText("0.0");
 62:         }
 63:         else
 64:             inputOutputField.setText("Error in adder code.");
 65:     }
 66: 
 67:     private static double stringToDouble(String stringObject)
 68:     {
 69:         return Double.parseDouble(stringObject.trim( ));
 70:     }
 71: }
 72: 
 73: 
 74: 
 75: 
 76: 
 77: