基于JavaSwing的简单计算器
立即下载
资源介绍:
基于JavaSwing的简单计算器
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame {
private JTextField display;
public Calculator() {
super("简易计算器");
// 设置布局
setLayout(new BorderLayout());
// 创建显示区域
display = new JTextField();
display.setEditable(false);
add(display, BorderLayout.NORTH);
display.setFont(new Font("Serif", Font.PLAIN, 40));
add(display, BorderLayout.NORTH);
// 创建面板以放置按钮
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
// 按钮数组
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};
// 添加按钮到面板
for (String buttonText : buttons) {
JButton button = new JButton(buttonText);
button.addActionListener(new ButtonListener());
panel.add(button);
}
// 将面板添加到框架
add(panel, BorderLayout.CENTER);
// 设置窗口属性
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// 按钮监听器
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("C".equals(command)) {
display.setText("");
} else if ("=".equals(command)) {
try {
String text = display.getText().replace('÷', '/').replace('×', '*');
double result = evaluateExpression(text);
display.setText(String.valueOf(result));
} catch (Exception ex) {
display.setText("错误");
}
} else {
display.setText(display.getText() + command);
}
}
private double evaluateExpression(String expression) {
// 这里可以使用脚本引擎来计算表达式
javax.script.ScriptEngineManager mgr = new javax.script.ScriptEngineManager();
javax.script.ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
return ((Number) engine.eval(expression)).doubleValue();
} catch (javax.script.ScriptException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
new Calculator();
}
}