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.

98 lines
2.7 KiB

2 months ago
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 double num1 = 0, num2 = 0, result = 0;
private String operation = "";
public Calculator() {
setTitle("简易计算器");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 显示屏
display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
// 按钮面板
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 10, 10));
String[] buttons = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "C", "0", "=", "+"};
for (String text : buttons) {
JButton button = new JButton(text);
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("C")) {
clearDisplay();
} else if (command.equals("=")) {
calculateResult();
} else {
handleInput(command);
}
}
private void handleInput(String input) {
if (input.matches("[0-9]")) {
display.setText(display.getText() + input);
} else {
operation = input;
num1 = Double.parseDouble(display.getText());
display.setText("");
}
}
private void calculateResult() {
num2 = Double.parseDouble(display.getText());
switch (operation) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
display.setText("Error");
return;
}
break;
case "%":
result = num1 % num2;
break;
}
display.setText(String.valueOf(result));
}
private void clearDisplay() {
display.setText("");
num1 = 0;
num2 = 0;
result = 0;
operation = "";
}
public static void main(String[] args) {
new Calculator();
}
}