📅  最后修改于: 2023-12-03 15:16:39.853000             🧑  作者: Mango
JFrame 计算器是一个基于 Java Swing GUI 编写的计算器应用程序,它允许用户进行基本的数学运算,例如加、减、乘、除等。本应用程序包含一个简单的用户界面,使得用户可以轻松地输入和计算数学表达式。JFrame 计算器还提供了一个用于清除输入的按钮,以及一个可以撤消上一步操作的按钮。下面将介绍其主要特点:
以下是 JFrame 计算器的代码片段:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JFrameCalculator extends JFrame implements ActionListener {
private JTextField resultField;
private JButton clearButton;
private JButton undoButton;
private Double result;
public JFrameCalculator() {
super("JFrame Calculator");
//设置布局
setLayout(new BorderLayout());
//设置结果区域
resultField = new JTextField("0");
resultField.setHorizontalAlignment(JTextField.RIGHT);
resultField.setEditable(false);
add(resultField, BorderLayout.NORTH);
//设置键盘区域
JPanel keyboardPanel = new JPanel();
keyboardPanel.setLayout(new GridLayout(4, 4, 5, 5));
//添加数字键
for (int i = 1; i <= 9; i++) {
addButton(keyboardPanel, String.valueOf(i));
}
//添加运算符键
addButton(keyboardPanel, "+");
addButton(keyboardPanel, "-");
addButton(keyboardPanel, "*");
addButton(keyboardPanel, "/");
addButton(keyboardPanel, ".");
addButton(keyboardPanel, "0");
//添加特殊按钮
undoButton = addButton(keyboardPanel, "undo");
clearButton = addButton(keyboardPanel, "C");
add(keyboardPanel, BorderLayout.CENTER);
//设置窗口属性
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* 创建并添加按钮到键盘面板上。
*/
private JButton addButton(JPanel panel, String buttonText) {
JButton button = new JButton(buttonText);
button.addActionListener(this);
panel.add(button);
return button;
}
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("C")) {
resultField.setText("0");
result = null;
} else if (action.equals("undo")) {
String text = resultField.getText();
if (text.length() == 1 || (result != null && text.length() == String.valueOf(result).length())) {
resultField.setText("0");
} else {
resultField.setText(text.substring(0, text.length() - 1));
}
} else {
String currentText = resultField.getText();
String newText = currentText.equals("0") ? action : currentText + action;
resultField.setText(newText);
try {
result = Double.parseDouble(newText);
} catch (NumberFormatException ex) {
// Ignore non-numeric values
}
}
}
public static void main(String[] args) {
new JFrameCalculator();
}
}
以上是完整源代码的部分片段,其中包括创建和添加按钮、处理用户输入以及更新结果区域等重要功能。