import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private JPanel panel;
private StringBuilder currentInput;
private double result;
private String operator;
public Calculator() {
// Frame settings
setTitle("Calculator");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Display settings
display = new JTextField();
display.setEditable(false);
display.setFont(new Font("Arial", Font.BOLD, 24));
add(display, BorderLayout.NORTH);
// Button panel settings
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
// Create and add buttons
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 24));
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
currentInput = new StringBuilder();
result = 0;
operator = "";
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("0123456789.".contains(command)) {
currentInput.append(command);
display.setText(currentInput.toString());
} else if (command.equals("=")) {
calculate();
display.setText(String.valueOf(result));
currentInput.setLength(0);
} else {
if (currentInput.length() > 0) {
calculate();
operator = command;
display.setText(String.valueOf(result));
currentInput.setLength(0);
}
}
}
private void calculate() {
double input = currentInput.length() > 0 ? Double.parseDouble(currentInput.toString()) : 0;
switch (operator) {
case "+":
result += input;
break;
case "-":
result -= input;
break;
case "*":
result *= input;
break;
case "/":
result /= input;
break;
default:
result = input;
break;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Calculator calculator = new Calculator();
calculator.setVisible(true);
});
}
}
javac Calculator.java
java Calculator