简易计算器通过Swing实现,支持四则运算与清屏删除功能。1. 使用JFrame构建窗口,JTextField显示内容,JPanel配合GridLayout布局按钮;2. 定义currentInput、previousValue、operation等变量管理计算状态;3. 为按钮添加ActionListener监听输入,区分数字、操作符与控制命令;4. 数字追加到当前输入,操作符存储并准备下一次输入,等号触发calculate方法执行运算,除零弹出提示;5. 主类中初始化界面组件并启动程序。可扩展小数点、连续计算与键盘输入。

实现一个简易计算器项目是学习Java基础语法、事件处理和Swing图形界面的好方法。下面是一个基于Java Swing的简易计算器实现步骤和完整代码示例。
这个简易计算器支持以下功能:
Java的Swing库可以用来创建窗口和按钮等GUI组件。我们需要一个主窗口(JFrame),一个显示结果的文本框(JTextField),以及多个按钮(JButton)组成数字和操作符面板。
关键组件说明:
立即学习“Java免费学习笔记(深入)”;
计算器的核心在于解析用户输入并执行运算。我们采用“中缀表达式”方式,记录当前输入的数字、操作符和前一个数值,点击“=”时进行计算。
为简化逻辑,使用以下变量:
以下是完整的Java代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame {
private JTextField display;
private String currentInput;
private double previousValue;
private String operation;
private boolean startNewInput;
public SimpleCalculator() {
// 初始化变量
currentInput = "";
previousValue = 0;
operation = "";
startNewInput = true;
// 设置窗口
setTitle("简易计算器");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 显示屏
display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setFont(new Font("Arial", Font.PLAIN, 24));
add(display, BorderLayout.NORTH);
// 按钮面板
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};
for (String text : buttons) {
JButton btn = new JButton(text);
btn.setFont(new Font("Arial", Font.BOLD, 18));
btn.addActionListener(new ButtonClickListener());
buttonPanel.add(btn);
}
add(buttonPanel, BorderLayout.CENTER);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {
// 数字输入
if (startNewInput) {
currentInput = "";
display.setText("");
startNewInput = false;
}
currentInput += command;
display.setText(currentInput);
} else if (command.equals("C")) {
// 清空
currentInput = "";
previousValue = 0;
operation = "";
startNewInput = true;
display.setText("");
} else if (isOperator(command)) {
// 操作符处理
if (!currentInput.isEmpty()) {
previousValue = Double.parseDouble(currentInput);
}
operation = command;
startNewInput = true;
} else if (command.equals("=")) {
// 计算结果
if (!currentInput.isEmpty() && !operation.isEmpty()) {
double currentValue = Double.parseDouble(currentInput);
double result = calculate(previousValue, currentValue, operation);
display.setText(String.valueOf(result));
currentInput = String.valueOf(result);
startNewInput = true;
}
}
}
private boolean isOperator(String op) {
return op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/");
}
private double calculate(double a, double b, String op) {
switch (op) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/":
if (b == 0) {
JOptionPane.showMessageDialog(null, "除数不能为零!");
return 0;
}
return a / b;
default: return 0;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
new SimpleCalculator().setVisible(true);
});
}
}将上述代码保存为 SimpleCalculator.java,编译并运行即可看到图形界面。
可进一步优化的功能包括:
基本上就这些。这个项目不复杂但容易忽略细节,比如状态管理、除零判断和输入控制。掌握它有助于理解Java GUI编程的基本模式。
以上就是如何使用Java实现简易计算器项目的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号