// Step 1: import the necessary classes

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

// Step 2:  Extend JFrame class
public class Calculator extends JFrame
{
		
    //Step 3: Declare all components that make application's interface
	
    JTextField operand1 = new JTextField(10);
    JTextField operand2 = new JTextField(10);

    JTextField result = new JTextField(10);

    JButton addOperation = new JButton("Add");
    JButton subOperation = new JButton("Sub");


    //Step 4: Define constructor
    public Calculator() 
    {
	 super.setTitle("Calculator");
	 
         // Step 5: instantiate a container for graphical components
         Container c = getContentPane();
	 
         // Step 6: Specify the layout : We will use a simple one
         c.setLayout( new FlowLayout() );

         // Step 7: add the individual components to the container
         c.add(operand1);
         c.add(operand2);
         c.add(result);
         
         // Step 8: Event generating components need handlers
                   // add the listeners and then add them to the container
         
         // we add an anonymous handler inner class to addOperation button
         addOperation.addActionListener (new ActionListener()
	     { public void actionPerformed(ActionEvent e)
		 { int sum = Integer.parseInt(operand1.getText()) + 
                             Integer.parseInt(operand2.getText());  
		 result.setText((new Integer(sum)).toString());}});

         c.add(addOperation);
          
         //we add named object bh of inner class BottonHandler to subOperation 
         ButtonHandler bh = new ButtonHandler();
         subOperation.addActionListener(bh);

         c.add(subOperation);
        
        //Step 9: set the size and background of the container
        setSize(170,200);
	setBackground(Color.yellow);
        // Step 10: display it
	show();
    }	
	
	//Main method, Instantiates Calculator
	public static void main(String[] args)
	{
		Calculator app = new Calculator();

                // Step 11: Window related operation management    
		app.addWindowListener(
		     new WindowAdapter() {
					      
	       public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
		     );
	}

    // Step 12: Inner class for button action handling
    class ButtonHandler implements ActionListener
    {      
 	    public void actionPerformed(ActionEvent e)
		{ int diff = Integer.parseInt(operand1.getText()) -
		      Integer.parseInt(operand2.getText());
		result.setText((new Integer(diff)).toString());}
    }
}
 
