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.

110 lines
3.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private final JTextField textField; // 显示输入和结果的文本框
private double result = 0; // 计算结果
private String operator = ""; // 运算符
private boolean calculating = true; // 是否正在计算中
public Calculator() {
setTitle("计算器");
textField = new JTextField("0");
textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT); // 右对齐显示
textField.setFont(new Font("Arial", Font.BOLD, 24)); // 增加文本框字体大小
add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 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.setFont(new Font("Arial", Font.BOLD, 18)); // 增加按钮字体大小
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 500); // 设置窗口大小为宽800像素高500像素
setLocationRelativeTo(null); // 窗口居中显示
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ('0' <= command.charAt(0) && command.charAt(0) <= '9' || command.equals(".")) {
if (calculating) {
textField.setText(command);
calculating = false;
} else {
textField.setText(textField.getText() + command);
}
} else {
switch (command) {
case "C":
textField.setText("0");
operator = "";
result = 0;
calculating = true;
break;
case "+":
case "-":
case "*":
case "/":
if (!calculating) {
result = Double.parseDouble(textField.getText());
operator = command;
calculating = true;
}
break;
case "=":
if (!calculating) {
calculate(Double.parseDouble(textField.getText()));
}
break;
}
}
}
private void calculate(double n) {
switch (operator) {
case "+":
result += n;
break;
case "-":
result -= n;
break;
case "*":
result *= n;
break;
case "/":
if (n != 0) {
result /= n;
} else {
JOptionPane.showMessageDialog(this, "除数不能为0");
return;
}
break;
}
textField.setText("" + result);
operator = "";
calculating = true;
}
public static void main(String[] args) {
new Calculator();
}
}