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.
Textcpt/Calculator.java

98 lines
3.0 KiB

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 textField;
private double num1, num2, result;
private String operator;
public Calculator() {
// 设置窗口基本属性
setTitle("计算器");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 创建文本框
textField = new JTextField();
textField.setFont(new Font("Arial", Font.PLAIN, 24));
add(textField, BorderLayout.NORTH);
// 创建按钮面板
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4, 10, 10));
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+",
"%", "(", ")", ""
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.PLAIN, 24));
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "C":
textField.setText("");
break;
case "=":
num2 = Double.parseDouble(textField.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
textField.setText("错误: 除以零");
return;
}
result = num1 / num2;
break;
case "%":
result = num1 % num2;
break;
}
textField.setText(String.valueOf(result));
break;
case "+":
case "-":
case "*":
case "/":
case "%":
num1 = Double.parseDouble(textField.getText());
operator = command;
textField.setText("");
break;
default:
textField.setText(textField.getText() + command);
break;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Calculator calculator = new Calculator();
calculator.setVisible(true);
});
}
}