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.
| 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. |
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);
});
}
}
Calculator.java.javac Calculator.java
java Calculator
setTitle("Java Calculator");
setSize(350, 450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
These statements set the window title, dimensions, and closing behavior.
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.
double number =
Double.parseDouble(display.getText());
The display contains text. Double.parseDouble()
converts that text into a numeric value for calculation.
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.
private void clearCalculator() {
display.setText("0");
firstNumber = 0;
operator = "";
startNewNumber = true;
}
This method resets the display and the calculator's stored state.
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 |
After completing the basic project, try adding these features:
Choose the correct answer for each question.