Java awt program to create a calculator


In this program, You will learn how to create a simple calculator using awt in java.


20 = 10 + 10

10 = 20 - 10

Example: How to create a simple calculator using awt in java.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class Test implements ActionListener {

    Button b1, b2, b3, b4;
    TextField t1, t2;
    Label lb3;
    Frame f;

    Test() {

        f = new Frame("Simple awt Calculator");

        t1 = new TextField();
        t1.setBounds(90, 50, 150, 30);
        f.add(t1);

        t2 = new TextField();
        t2.setBounds(90, 80, 150, 30);
        f.add(t2);

        lb3 = new Label("Result :");
        lb3.setBounds(90, 140, 150, 30);
        f.add(lb3);

        b1 = new Button("+");
        b1.setBounds(50, 200, 100, 30);
        f.add(b1);

        b2 = new Button("-");
        b2.setBounds(150, 200, 100, 30);
        f.add(b2);

        b3 = new Button("*");
        b3.setBounds(250, 200, 100, 30);
        f.add(b3);

        b4 = new Button("/");
        b4.setBounds(350, 200, 100, 30);
        f.add(b4);

        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);

        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });

        f.setLayout(null);
        f.setSize(600, 500);
        f.setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {

        int a = Integer.parseInt(t1.getText());
        int b = Integer.parseInt(t2.getText());
        int c = 0;

        if (e.getSource().equals(b1)) {
            c = a + b;
        } else if (e.getSource().equals(b2)) {
            c = a - b;
        } else if (e.getSource().equals(b3)) {
            c = a * b;
        } else if (e.getSource().equals(b4)) {
            c = a / b;
        }
        lb3.setText(String.valueOf("Result is :   " + c));
    }

    public static void main(String args[]) {
        Test t = new Test();
    }
}

Output:

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.