Java Calculator Project
100%

Java Calculator Project Using Swing

In this project, you will build a simple desktop calculator using Java Swing. The calculator will perform addition, subtraction, multiplication, and division through a graphical user interface.

Project Requirements: Basic Java, classes, methods, event handling, and Swing components.

1. Project Features

  • Graphical calculator window.
  • Display field for numbers and results.
  • Number buttons from 0 to 9.
  • Addition (+), subtraction (-), multiplication (*), and division (/).
  • Clear (C) button.
  • Decimal point support.
  • Error message for division by zero.
  • Responsive button arrangement using a layout manager.

2. Swing Components Used

Component Purpose
JFrame Creates the calculator window.
JTextField Displays the current number and result.
JButton Creates clickable calculator buttons.
JPanel Groups the buttons together.
GridLayout Arranges buttons in rows and columns.
ActionListener Handles button-click events.

3. Complete Calculator Program

Create a file named Calculator.java and copy the following complete program into it.

import javax.swing.*;
import java.awt.*;
import java.math.BigDecimal;

public class Calculator extends JFrame {

    private final JTextField display;

    private double firstNumber = 0;
    private String operator = "";
    private boolean startNewNumber = true;

    public Calculator() {
        setTitle("Java Calculator");
        setSize(350, 450);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        display = new JTextField("0");
        display.setEditable(false);
        display.setHorizontalAlignment(JTextField.RIGHT);
        display.setFont(new Font("Arial", Font.BOLD, 28));
        display.setMargin(new Insets(10, 10, 10, 10));

        JPanel buttonPanel = new JPanel(new GridLayout(4, 4, 5, 5));

        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "C", "0", ".", "+"
        };

        for (String text : buttons) {
            JButton button = new JButton(text);
            button.setFont(new Font("Arial", Font.BOLD, 20));

            button.addActionListener(e -> handleButton(text));

            buttonPanel.add(button);
        }

        JButton equalsButton = new JButton("=");
        equalsButton.setFont(new Font("Arial", Font.BOLD, 22));
        equalsButton.addActionListener(e -> calculateResult());

        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(equalsButton, BorderLayout.CENTER);

        setLayout(new BorderLayout(8, 8));
        add(display, BorderLayout.NORTH);
        add(buttonPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private void handleButton(String text) {
        if (text.equals("C")) {
            clearCalculator();
        } else if ("+-*/".contains(text)) {
            selectOperator(text);
        } else {
            enterDigit(text);
        }
    }

    private void enterDigit(String digit) {
        if (startNewNumber) {
            display.setText(digit.equals(".") ? "0." : digit);
            startNewNumber = false;
            return;
        }

        String current = display.getText();

        if (digit.equals(".")) {
            if (!current.contains(".")) {
                display.setText(current + ".");
            }
        } else if (current.equals("0")) {
            display.setText(digit);
        } else {
            display.setText(current + digit);
        }
    }

    private void selectOperator(String selectedOperator) {
        try {
            firstNumber = Double.parseDouble(display.getText());
            operator = selectedOperator;
            startNewNumber = true;
        } catch (NumberFormatException ex) {
            showError("Invalid number.");
        }
    }

    private void calculateResult() {
        if (operator.isEmpty()) {
            return;
        }

        try {
            double secondNumber =
                Double.parseDouble(display.getText());

            double result;

            switch (operator) {
                case "+":
                    result = firstNumber + secondNumber;
                    break;

                case "-":
                    result = firstNumber - secondNumber;
                    break;

                case "*":
                    result = firstNumber * secondNumber;
                    break;

                case "/":
                    if (secondNumber == 0) {
                        showError("Cannot divide by zero.");
                        clearCalculator();
                        return;
                    }

                    result = firstNumber / secondNumber;
                    break;

                default:
                    return;
            }

            if (!Double.isFinite(result)) {
                showError("Result is outside the supported range.");
                clearCalculator();
                return;
            }

            display.setText(
                BigDecimal.valueOf(result)
                    .stripTrailingZeros()
                    .toPlainString()
            );

            operator = "";
            startNewNumber = true;

        } catch (NumberFormatException ex) {
            showError("Invalid number.");
            clearCalculator();
        }
    }

    private void clearCalculator() {
        display.setText("0");
        firstNumber = 0;
        operator = "";
        startNewNumber = true;
    }

    private void showError(String message) {
        JOptionPane.showMessageDialog(
            this,
            message,
            "Calculator Error",
            JOptionPane.ERROR_MESSAGE
        );
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Calculator calculator = new Calculator();
            calculator.setVisible(true);
        });
    }
}
Result: This program creates a working graphical calculator with number buttons, four arithmetic operators, a decimal point, a clear button, and an equals button.

4. How to Run the Project

  1. Install a JDK on your computer.
  2. Open your Java IDE or a terminal.
  3. Create a file named Calculator.java.
  4. Paste the complete program into the file.
  5. Save the file.
  6. Compile the program using the Java compiler.
  7. Run the program and test each button.
Compile Using the Terminal
javac Calculator.java
Run the Calculator
java Calculator
Note: Run this desktop application on a computer with a graphical environment. It will not display its Swing window in a standard text-only terminal.

5. Understanding the Important Code

A. Creating the Window
setTitle("Java Calculator");
setSize(350, 450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

These statements set the window title, dimensions, and closing behavior.

B. Creating Buttons
JButton button = new JButton(text);
button.addActionListener(e -> handleButton(text));

The first statement creates a button. The second registers an event handler that runs when the button is clicked.

C. Reading the Display
double number =
    Double.parseDouble(display.getText());

The display contains text. Double.parseDouble() converts that text into a numeric value for calculation.

D. Performing Arithmetic
switch (operator) {
    case "+":
        result = firstNumber + secondNumber;
        break;

    case "-":
        result = firstNumber - secondNumber;
        break;

    case "*":
        result = firstNumber * secondNumber;
        break;

    case "/":
        result = firstNumber / secondNumber;
        break;
}

The switch statement chooses the calculation based on the selected operator. The complete project also checks for division by zero before dividing.

E. Clearing the Calculator
private void clearCalculator() {
    display.setText("0");
    firstNumber = 0;
    operator = "";
    startNewNumber = true;
}

This method resets the display and the calculator's stored state.

6. Test Cases

Use these examples to test the calculator.

Operation Expected Result
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2
2.5 + 1.5 = 4
10 / 0 = Error message
Current limitation: This is a basic calculator. It performs one operation at a time, does not support keyboard input, and does not implement operator precedence or chained calculations.

7. Project Improvements

After completing the basic project, try adding these features:

  1. Add percentage calculation.
  2. Add positive/negative number support using a +/- button.
  3. Add a backspace button to delete the last digit.
  4. Add keyboard support for numbers and operators.
  5. Improve the user interface with custom colors and fonts.
  6. Add square and square-root operations.
  7. Support repeated calculations.
  8. Add a calculation history panel.

8. Practice Assignments

  1. Change the calculator window size and title.
  2. Change the font size of the display.
  3. Set different colors for number and operator buttons.
  4. Add a backspace button.
  5. Add a square button.
  6. Add a square-root button.
  7. Allow the user to perform calculations using the keyboard.
  8. Improve the program so the user can perform chained calculations.

Java Calculator Project - Quick Quiz

Choose the correct answer for each question.

1. Which Swing component creates a clickable button?



2. Which method registers a button-click listener?



3. What should a calculator do before dividing by zero?