Simple calculator program in java using swing

Simple calculator program in java using swing

This code is for creating a simple calculator using Java Swing.

Creating GUI Components: The code creates a JFrame (window) with a JTextField (for displaying input and result) and several JButtons (for numbers, arithmetic operators, and clear functionality).

Layout and Size: It sets the bounds (position and size) for each component within the JFrame.

Action Listeners: Action listeners are added to each button to handle user interactions. When a button is clicked, its corresponding action is triggered.

For numeric buttons (0-9), a single action listener is shared among all of them. When a numeric button is clicked, the current text in the JTextField is retrieved, and the clicked number is appended to it.

For operator buttons (+, -, *, /), another action listener is shared among them. When an operator button is clicked, it appends the operator to the current text in the JTextField, separating it with spaces.

The "Clear" button (C) has a separate action listener to clear the text field when clicked.

The "=" button performs the calculation based on the expression entered in the text field. It parses the expression, evaluates it, and displays the result in the text field.

Performing Calculations: The calculation is performed when the "=" button is clicked. It extracts the expression from the text field, splits it into parts (operands and operator), performs the arithmetic operation, and displays the result.

Displaying the GUI: Finally, all the components are added to the JFrame, the layout is set to null (custom positioning), and the JFrame is set to be visible.




import java.awt.event.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame f = new JFrame("Calculator");
JTextField t1 = new JTextField();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b0 = new JButton("0");
JButton bclear = new JButton("C");
JButton bsum = new JButton("+");
JButton bmin = new JButton("-");
JButton bmul = new JButton("*");
JButton bdiv = new JButton("/");
JButton beq = new JButton("=");
t1.setBounds(5, 20, 300, 20);
b1.setBounds(10, 60, 50, 30);
b2.setBounds(70, 60, 50, 30);
b3.setBounds(130, 60, 50, 30);
b4.setBounds(10, 100, 50, 30);
b5.setBounds(70, 100, 50, 30);
b6.setBounds(130, 100, 50, 30);
b7.setBounds(10, 140, 50, 30);
b8.setBounds(70, 140, 50, 30);
b9.setBounds(130, 140, 50, 30);
b0.setBounds(10, 180, 50, 30);
bclear.setBounds(70, 180, 50, 30);
bsum.setBounds(190, 60, 50, 30);
bmin.setBounds(190, 100, 50, 30);
bmul.setBounds(190, 140, 50, 30);
bdiv.setBounds(190, 180, 50, 30);
beq.setBounds(130, 180, 50, 30);
ActionListener numericListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String currentText = t1.getText();
JButton button = (JButton) e.getSource();
t1.setText(currentText + button.getText());
}
};
b1.addActionListener(numericListener);
b2.addActionListener(numericListener);
b3.addActionListener(numericListener);
b4.addActionListener(numericListener);
b5.addActionListener(numericListener);
b6.addActionListener(numericListener);
b7.addActionListener(numericListener);
b8.addActionListener(numericListener);
b9.addActionListener(numericListener);
b0.addActionListener(numericListener);
bclear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t1.setText("");


}
});
ActionListener operatorListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String currentText = t1.getText();
JButton button = (JButton) e.getSource();
t1.setText(currentText + " " + button.getText() + " ");
}
};
bsum.addActionListener(operatorListener);
bmin.addActionListener(operatorListener);
bmul.addActionListener(operatorListener);
bdiv.addActionListener(operatorListener);
beq.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String expression = t1.getText();
String[] parts = expression.split(" ");
double result = Double.parseDouble(parts[0]);
char operator = parts[1].charAt(0);
double operand = Double.parseDouble(parts[2]);
switch (operator) {
case '+':
result += operand;

break;
case '-':
result -= operand;

break;
case '*':
result *= operand;

break;
case '/':
if (operand != 0)
result /= operand;
else
t1.setText("Error: Division by zero");
break;
default:
t1.setText("Error: Invalid operator");
return;
}
t1.setText(Double.toString(result));
}
});
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(b0);
f.add(bclear);
f.add(bsum);
f.add(bmin);
f.add(bmul);

f.add(bdiv);
f.add(beq);
f.add(t1);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}





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

This imports necessary packages from Java's standard library: java.awt.event.* for event handling and javax.swing.* for creating GUI components.


public class Main {
This declares a public class named Main, which serves as the entry point for the program.


public static void main(String[] args) {
This declares the main method, which is the starting point of execution for Java programs.


JFrame f = new JFrame("Calculator");
This creates a new JFrame (window) with the title "Calculator".


JTextField t1 = new JTextField();
This creates a JTextField, which is used for displaying and inputting text.


JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
// Similar lines for other number buttons (b3 to b9) and operation buttons (b0 to beq)
These lines create JButtons for numbers (b1 to b9), digits (b0), and arithmetic operations (+, -, *, /, =, C).


t1.setBounds(5, 20, 300, 20);
This sets the position and size of the text field within the JFrame.


b1.setBounds(10, 60, 50, 30);
// Similar lines for other buttons
These lines set the position and size of each button within the JFrame.


ActionListener numericListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String currentText = t1.getText();
        JButton button = (JButton) e.getSource();
        t1.setText(currentText + button.getText());
    }
};
This creates an ActionListener for numeric buttons. When a numeric button is clicked, it retrieves the current text from the text field, appends the clicked number to it, and updates the text field.


b1.addActionListener(numericListener);
// Similar lines for other numeric buttons
These lines add the numeric listener to each numeric button.


bclear.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        t1.setText("");
    }
});
This adds an ActionListener to the clear button. When clicked, it clears the text field by setting its text to an empty string.


ActionListener operatorListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String currentText = t1.getText();
        JButton button = (JButton) e.getSource();
        t1.setText(currentText + " " + button.getText() + " ");
    }
};
This creates an ActionListener for operator buttons. When an operator button is clicked, it retrieves the current text, appends the clicked operator with spaces around it, and updates the text field.


bsum.addActionListener(operatorListener);
// Similar lines for other operator buttons
These lines add the operator listener to each operator button.


beq.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String expression = t1.getText();
        String[] parts = expression.split(" ");
        double result = Double.parseDouble(parts[0]);
        char operator = parts[1].charAt(0);
        double operand = Double.parseDouble(parts[2]);
        switch (operator) {
            case '+':
                result += operand;
                break;
            case '-':
                result -= operand;
                break;
            case '*':
                result *= operand;
                break;
            case '/':
                if (operand != 0)
                    result /= operand;
                else
                    t1.setText("Error: Division by zero");
                break;
            default:
                t1.setText("Error: Invalid operator");
                return;
        }
        t1.setText(Double.toString(result));
    }
});
This adds an ActionListener to the equals button (=). When clicked, it performs the calculation based on the expression entered in the text field, handles errors like division by zero or invalid operator, and displays the result in the text field.


f.add(b1);
// Similar lines for adding other buttons and text field to the JFrame
These lines add all the buttons and the text field to the JFrame.


f.setSize(400, 400);
This sets the size of the JFrame.


f.setLayout(null);
This sets the layout manager of the JFrame to null, meaning the components are manually positioned.


f.setVisible(true);
This makes the JFrame visible.


}
}
These lines close the main method and the class definition.