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.
CZYYCCKK/SimpleCalculator.java

89 lines
2.8 KiB

package Calculate;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class SimpleCalculator extends JFrame {
private JTextField inputField; // 输入显示区域
public SimpleCalculator() {
createUI();
}
private void createUI() {
// 设置窗口布局
setLayout(new BorderLayout());
// 创建输入显示区域
inputField = new JTextField("0");
inputField.setEditable(false);
inputField.setHorizontalAlignment(JTextField.RIGHT);
add(inputField, BorderLayout.NORTH);
// 创建面板用于放置按钮
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4, 5, 5)); // 设置间距
// 创建数字和运算符按钮
String[] buttons = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+", "C", "Backspace"};
for (String b : buttons) {
JButton button = new JButton(b);
panel.add(button);
button.addActionListener(e -> press(e.getActionCommand()));
}
// 添加面板到窗口
add(panel, BorderLayout.CENTER);
// 设置窗口属性
setSize(300, 400); // 设置窗口大小
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Simple Calculator");
setVisible(true);
}
private void press(String command) {
if ("C".equals(command)) {
clear();
} else if ("Backspace".equals(command)) {
backspace();
} else if ("=".equals(command)) {
calculate();
} else {
if (inputField.getText().equals("0") && !command.equals(".")) {
inputField.setText(command);
} else {
inputField.setText(inputField.getText() + command);
}
}
}
private void clear() {
inputField.setText("0");
}
private void backspace() {
String currentText = inputField.getText();
if (!currentText.isEmpty()) {
inputField.setText(currentText.substring(0, currentText.length() - 1));
}
}
private void calculate() {
String expression = inputField.getText();
try {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
Object result = engine.eval(expression);
inputField.setText(result.toString());
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Invalid input", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SimpleCalculator::new);
}
}