swing计算器连续计算
时间: 2023-09-10 11:04:51 浏览: 54
要实现swing计算器的连续计算功能,可以考虑以下步骤:
1. 定义一个变量来存储上一次计算的结果。
2. 在等号按钮的事件处理方法中,先将当前表达式的值计算出来,并将其赋值给上一次计算的结果变量。
3. 将当前表达式的值显示在计算器的结果文本框中。
4. 在数字按钮的事件处理方法中,如果结果文本框中已经显示了上一次计算的结果,则清空结果文本框,开始新的计算。
以下是一个简单的示例代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField inputField;
private double lastResult;
public Calculator() {
inputField = new JTextField(20);
inputField.setEditable(false);
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.addActionListener(this);
buttonPanel.add(button);
}
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPane.add(inputField, BorderLayout.NORTH);
contentPane.add(buttonPanel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(contentPane);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
String input = inputField.getText();
double result = calculate(input);
lastResult = result;
inputField.setText(Double.toString(result));
} else if ("0123456789.".indexOf(command) != -1) {
if (inputField.getText().equals(Double.toString(lastResult))) {
inputField.setText(command);
} else {
inputField.setText(inputField.getText() + command);
}
} else {
inputField.setText(inputField.getText() + " " + command + " ");
}
}
private double calculate(String input) {
// TODO: 实现计算逻辑
}
public static void main(String[] args) {
new Calculator();
}
}
```
在上面的代码中,lastResult 变量用来存储上一次计算的结果。在等号按钮的事件处理方法中,先将当前表达式的值计算出来,并将其赋值给 lastResult 变量。在数字按钮的事件处理方法中,如果结果文本框中已经显示了上一次计算的结果,则清空结果文本框,开始新的计算。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)