Saturday, 5 January 2013

Add subtract divide multiply in java

package calculator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class cal extends JFrame implements ActionListener
{
    // cal cl=new cal();
    int s3,s1,s2;
    JLabel num1,num2,res,rs;
    JPanel panel1,panel2;
    JButton add,sub,mul,div;
    JTextField n1,n2,n3;
    cal()
    {
     panel1=new JPanel(new FlowLayout());
      panel2=new JPanel(new FlowLayout());
     num1=new JLabel("Number1");
     num2=new JLabel("Nmber2");
     res=new JLabel("Result");
     rs=new JLabel("rgjfjj");
     n1=new JTextField(5);
     n2=new JTextField(5);
     n3=new JTextField(5);
     add=new JButton("ADD");
     sub=new JButton("SUB");
     mul=new JButton("MUL");
     div=new JButton("DIV");
    
     add.addActionListener(this);
     mul.addActionListener(this);
     sub.addActionListener(this);
     div.addActionListener(this);
   Component add1= panel1.add(num1);
  Component add2=  panel1.add(n1);
   Component add3= panel1.add(num2);
   Component add4= panel1.add(n2);
   Component add5= panel1.add(res);
    Component add6 = panel1. add(n3);
    Component add7 = panel2.   add(add);
    Component add8 = panel2.   add(sub);
    Component add9 = panel2.   add(mul);
    Component add10 = panel2.  add(div);
     add(panel1,BorderLayout.NORTH);
     add(panel2,BorderLayout.SOUTH);
    
    
      
     }
   
    public void actionPerformed(ActionEvent e)
   {
      int s1=Integer.parseInt(n1.getText());
      int s2=Integer.parseInt(n2.getText());
     
     
       if(e.getSource()==add)
       {
           s3=s1+s2;
      System.out.println(s3);
       n3.setText(Integer.toString(s3));
       }
       else if(e.getSource()==sub)
       {
           s3=s1-s2;
      System.out.println(s3);
       n3.setText(Integer.toString(s3));
       }
        else if(e.getSource()==div)
       {
           s3=s1/s2;
      System.out.println(s3);
       n3.setText(Integer.toString(s3));
       }
       else if(e.getSource()==mul)
       {
           s3=s1*s2;
      System.out.println(s3);
       n3.setText(Integer.toString(s3));
       }
}
}

public class Calculator {
  
    public static void main(String[] args) {
       cal cl=new cal();
       cl.setBounds(200, 150, 120, 550);
       cl.setTitle("calculator");
       cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       cl.setResizable(true);
       cl.setVisible(true);
       cl.setSize(500,200);
    }
}

No comments:

Post a Comment