java 简易计算器增加历史记录功能
时间: 2024-01-12 16:21:36 浏览: 32
以下是一个简易计算器增加历史记录功能的Java代码示例:
```java
import javax.swing.*;import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorWithHistory extends JFrame {
private JTextField result_Jtf;
private JButton CE;
private JButton history;
private JButton equal;
private String str = "";
private String[] historyArr = new String[5];
private int countEqu = 0;
public CalculatorWithHistory() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
result_Jtf = new JTextField();
result_Jtf.setEditable(false);
add(result_Jtf, BorderLayout.NORTH);
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(1, 2));
CE = new JButton("CE");
CE.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
str = ""; result_Jtf.setText(str);
}
});
history = new JButton("历史记录");
history.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBuilder historyStr = new StringBuilder();
for (int i = 0; i < historyArr.length; i++) {
if (historyArr[i] != null) {
historyStr.append(historyArr[i]).append("\n");
}
}
JOptionPane.showMessageDialog(null, historyStr.toString(), "历史记录", JOptionPane.INFORMATION_MESSAGE);
}
});
panel3.add(CE);
panel3.add(history);
add(panel3, BorderLayout.SOUTH);
JPanel panel1 = new JPanel();
panel1.setLayout(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(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String actionBut = e.getActionCommand();
str = str + actionBut;
result_Jtf.setText(str);
}
});
panel1.add(button);
}
add(panel1, BorderLayout.CENTER);
equal = new JButton("=");
equal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
str = calculate(str);
result_Jtf.setText(str);
countEqu = countEqu % 5;
historyArr[countEqu] = str;
countEqu++;
str = "";
}
});
add(equal, BorderLayout.EAST);
pack();
setVisible(true);
}
private String calculate(String expression) {
// 实现表达式求值的逻辑
// ...
return result;
}
public static void main(String[] args) {
new CalculatorWithHistory();
}
}
```