You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
3.7 KiB

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame {
private JTextField display;
private JPanel panel;
private double operand1 = 0;
private double operand2 = 0;
private char operator;
private boolean userIsTypingSecondNumber = false;
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Display text field
display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(SwingConstants.RIGHT);
add(display, BorderLayout.NORTH);
// Panel for buttons
panel = new JPanel();
panel.setLayout(new GridLayout(5, 4, 10, 10));
// Add numbers and operations to panel
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"C"
};
for (String text : buttons) {
JButton button = new JButton(text);
button.setFont(new Font("Verdana", Font.PLAIN, 24));
button.setFocusable(false);
panel.add(button);
button.addActionListener(new ButtonClickListener());
}
add(panel, BorderLayout.CENTER);
}
private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("0123456789.".contains(command)) {
display.setText(display.getText().concat(command));
} else if ("+-*/".contains(command)) {
operand1 = Double.parseDouble(display.getText());
operator = command.charAt(0);
userIsTypingSecondNumber = true;
display.setText(""); // Clear the display for the next number
} else if (command.equals("=")) {
if (userIsTypingSecondNumber) {
operand2 = Double.parseDouble(display.getText());
double result = 0;
switch (operator) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 != 0) {
result = operand1 / operand2;
} else {
display.setText("Error");
return;
}
break;
}
display.setText(String.valueOf(result));
operand1 = result; // Store the result for possible chain operations
userIsTypingSecondNumber = false; // Reset for next operation
}
} else if (command.equals("C")) {
display.setText("");
operand1 = 0;
operand2 = 0;
userIsTypingSecondNumber = false;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}