Create a Calculator using Java AWT

Create a Calculator us

ing Java AWT

In this tutorial, we will learn how to create a simple calculator using Java AWT (Abstract Window Toolkit). This calculator will perform basic arithmetic operations like addition, subtraction, multiplication, and division.

 

Introduction

AWT is a part of Java’s standard library used for creating graphical user interfaces (GUI). We will leverage AWT components like Frame, Panel, Button, and Text Field to build our calculator.

 

Steps to Solve the Problem

Step 1: Define the Class and Main Method
import java.awt.*;
import java.awt.event.*;

public class Calculator extends Frame implements ActionListener {
    // Declare components
    TextField display;
    Panel panel;
    String[] buttons = {
        "7", "8", "9", "/", 
        "4", "5", "6", "*", 
        "1", "2", "3", "-", 
        "0", ".", "=", "+"
    };
    Button[] button = new Button[buttons.length];
    String operand1 = "";
    String operator = "";
    boolean startNewNumber = true;

    public Calculator() {
        // Set layout for the frame
        setLayout(new BorderLayout());

        // Create display field
        display = new TextField();
        display.setEditable(false);
        add(display, BorderLayout.NORTH);

        // Create panel for buttons
        panel = new Panel();
        panel.setLayout(new GridLayout(4, 4));
        for (int i = 0; i < buttons.length; i++) {
            button[i] = new Button(buttons[i]);
            button[i].addActionListener(this);
            panel.add(button[i]);
        }
        add(panel, BorderLayout.CENTER);

        // Set frame properties
        setTitle("Calculator");
        setSize(400, 400);
        setVisible(true);

        // Add window listener to close the window
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent) {
                System.exit(0);
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();

        if (command.charAt(0) >= '0' && command.charAt(0) <= '9' || command.equals(".")) {
            if (startNewNumber) {
                display.setText(command);
                startNewNumber = false;
            } else {
                display.setText(display.getText() + command);
            }
        } else if (command.equals("=")) {
            double result = calculate(Double.parseDouble(operand1), Double.parseDouble(display.getText()), operator);
            display.setText("" + result);
            startNewNumber = true;
        } else {
            operand1 = display.getText();
            operator = command;
            startNewNumber = true;
        }
    }

    private double calculate(double operand1, double operand2, String operator) {
        switch (operator) {
            case "+": return operand1 + operand2;
            case "-": return operand1 - operand2;
            case "*": return operand1 * operand2;
            case "/": 
                if (operand2 != 0) return operand1 / operand2;
                else return 0; // Handle division by zero
            default: return 0;
        }
    }

    public static void main(String[] args) {
        new Calculator();
    }
}

Output Window

Step 2: Initialize the Components

  • Display Field: We create a TextField to display the input and result.
  • Panel for Buttons: We create a Panel   and set its layout to GridLayout  to arrange the buttons in a 4×4 grid

Step 3: Add Event Handling

We implement the ActionListener interface and override the actionPerformed method to handle button clicks. This method updates the display based on the input and performs calculations when the equal button is pressed.

Step 4: Perform Calculations

The calculate method takes two operands and an operator, performs the corresponding arithmetic operation, and returns the result.

Step 5: Display the Result

Finally, we display the result in the TextField.

Name the file name as Calculator.java Before running the above program

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top