Simple Calculator

Java Swing program that functions as a basic calculator. The calculator supports digits (0-9) and operations (+, -, *, /), and includes a text field to display the result. It also handles exceptions such as division by zero.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleCalculator extends JFrame implements ActionListener {

    private JTextField display;
    private double num1, num2, result;
    private char operator;

    public SimpleCalculator() {
        // Create the display field
        display = new JTextField();
        display.setEditable(false);
        display.setFont(new Font("Arial", Font.BOLD, 24));
        add(display, BorderLayout.NORTH);

        // Create the panel for buttons
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
        add(buttonPanel, BorderLayout.CENTER);

        // Add buttons for digits and operations
        String[] buttonLabels = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", "C", "=", "+"
        };

        for (String label : buttonLabels) {
            JButton button = new JButton(label);
            button.setFont(new Font("Arial", Font.BOLD, 20));
            button.addActionListener(this);
            buttonPanel.add(button);
        }

        // Set up the frame
        setTitle("Simple Calculator");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

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

        if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {
            display.setText(display.getText() + command);
        } else if (command.charAt(0) == 'C') {
            display.setText("");
        } else if (command.charAt(0) == '=') {
            try {
                num2 = Double.parseDouble(display.getText());
                switch (operator) {
                    case '+':
                        result = num1 + num2;
                        break;
                    case '-':
                        result = num1 - num2;
                        break;
                    case '*':
                        result = num1 * num2;
                        break;
                    case '/':
                        if (num2 == 0) {
                            throw new ArithmeticException("Cannot divide by zero");
                        }
                        result = num1 / num2;
                        break;
                }
                display.setText(String.valueOf(result));
            } catch (ArithmeticException ex) {
                display.setText("Error: " + ex.getMessage());
            } catch (NumberFormatException ex) {
                display.setText("Invalid input");
            }
        } else {
            try {
                num1 = Double.parseDouble(display.getText());
                operator = command.charAt(0);
                display.setText("");
            } catch (NumberFormatException ex) {
                display.setText("Invalid input");
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SimpleCalculator::new);
    }
}

Imports
  • javax.swing.*: Imports classes for building the GUI using Swing components like JFrame, JPanel, JButton, and JTextField.
  • java.awt.*: Imports classes for AWT (Abstract Window Toolkit) which is used for GUI layouts and other UI elements.
  • java.awt.event.*: Imports classes to handle events such as ActionEvent and ActionListener.

  • Class Definition
  • The class SimpleCalculator extends JFrame to create the main window of the calculator.
  • It implements ActionListener to handle button click events.

  • Instance Variables
  • display: A JTextField to display the input and result.
  • num1, num2, result: Variables to store the first operand, second operand, and the result of the calculation, respectively.
  • operator: A character to store the operator (+, -, *, /) selected by the user

  • Constructor

    Creating the Display Field:
    • display: Initializes the text field to show input and results.
    • setEditable(false): Ensures the user cannot edit the text field directly.
    • setFont: Sets the font for the text field.
    • add(display, BorderLayout.NORTH): Adds the text field to the top of the frame.
    Creating the Button Panel:
    • JPanel buttonPanel = new JPanel(): Initializes a panel to hold the buttons.
    • setLayout(new GridLayout(4, 4, 5, 5)): Sets a 4x4 grid layout with spacing between buttons.
    • add(buttonPanel, BorderLayout.CENTER): Adds the button panel to the center of the frame.

    Adding Buttons:

    • String[] buttonLabels: Array of labels for the buttons.
    • Loop: Iterates over the array to create and add buttons to the panel.
    • button.setFont(new Font("Arial", Font.BOLD, 20)): Sets the font for each button.
    • button.addActionListener(this): Registers the current instance as the listener for button clicks.
    • buttonPanel.add(button): Adds each button to the button panel.
    Setting Up the Frame:
    • setTitle("Simple Calculator"): Sets the title of the window.
    • setSize(400, 400): Sets the size of the window.
    • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the application exits when the window is closed.
    • setVisible(true): Makes the window visible.
    Handling Button Clicks
    1. Getting the Command:

      • String command = e.getActionCommand(): Retrieves the label of the button that was clicked.
    2. Handling Digit Buttons:

      • if (command.charAt(0) >= '0' && command.charAt(0) <= '9'): Checks if the button is a digit.
      • display.setText(display.getText() + command): Appends the digit to the display.
    3. Handling Clear Button:

      • else if (command.charAt(0) == 'C'): Checks if the button is "C" (clear).
      • display.setText(""): Clears the display.
    4. Handling Equals Button:

      • else if (command.charAt(0) == '='): Checks if the button is "=".
      • Try-Catch Block: Parses the second number, performs the calculation based on the operator, and updates the display with the result. Handles ArithmeticException for division by zero and NumberFormatException for invalid input.
    5. Handling Operator Buttons:

      • else: Handles the operator buttons (+, -, *, /).
      • Try-Catch Block: Parses the first number, stores the operator, and clears the display for the next input. Handles NumberFormatException for invalid input.
    Main Method
  • SwingUtilities.invokeLater: Ensures the GUI creation and updates are handled on the Event Dispatch Thread.
  • SimpleCalculator::new: Creates an instance of the SimpleCalculator class, which initializes the GUI and makes it visible.
  • Comments

    Popular posts from this blog

    KTU OOP LAB JAVA CSL 203 BTech CS S3 - Dr Binu V P

    Syllabus and Practice Questions KTU OOPS Lab Java CSL 203

    String Problems