A Java Program to make a simple calculator.



Hey Guys!!! Welcome once again.It's  Parth here.In this tutorial we are going to make a simple calculator which can perform addition,subtraction,multiplication,and division operation.For that you need 4 buttons,2 text field to insert input to the calc and a label to print the calculated input.I have used grid layout of 4X4.Here i have used the pannel of 300px X 300px, you can use your own size.

Let's start to program the calculator.

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{
            Button b1,b2,b3,b4;
            TextField t,tx;
            Label l;
            int n;
MyFrame()
            {
                       
                        t = new TextField(10);
                        tx = new TextField(10);
                        b1= new Button("+");
                        b2= new Button("-");
                        b3= new Button("*");
                        b4= new Button("/");
                        l = new Label("Ans");
                        setLayout(new GridLayout(4,4));
                       
                        add(t);
                        add(tx);                       
                        add(b1);
                        add(b2);
                        add(b3);
                        add(b4);
add(l);
                       
b1.addActionListener(this);
                        b2.addActionListener(this);
                        b3.addActionListener(this);
                        b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
            {           String a=t.getText();
                        int n1=Integer.parseInt(a);
                        String b=tx.getText();
                        int n2=Integer.parseInt(a);
                        String s=e.getActionCommand();
                       
                        if(s.equals("+"))
                        {
                                    n=n1+n2;
                        }
                        else if(s.equals("-"))
                        {
                                    n=n1-n2;
                        }
                        else if(s.equals("*"))
                        {
                                    n=n1*n2;
                        }
                        else if(s.equals("/"))
                        {
                                    n=n1/n2;
                        }                      
l.setText(n+" ");
}
}
class Demo
{
            public static void main(String args[])
            {          
                        MyFrame a=new MyFrame();
                        a.setSize(300,300);
                        a.setVisible(true);
            }
}

Output of this program is same as the above image.If you have any query comment below.

Comments