用java写一个简单计算器的窗口
时间: 2024-12-11 13:31:02 浏览: 11
在Java中创建一个简单的图形用户界面(GUI)计算器,我们可以使用Swing库,它是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 inputField;
private JButton[] buttons = new JButton[10];
private String[] operations = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "="};
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
setContentPane(panel);
panel.setLayout(new GridLayout(4, 4));
inputField = new JTextField(10);
panel.add(inputField);
for (int i = 0; i < operations.length; i++) {
buttons[i] = new JButton(operations[i]);
buttons[i].addActionListener(e -> doCalculation());
panel.add(buttons[i]);
}
JButton equalButton = new JButton("=");
equalButton.addActionListener(e -> performFinalCalculation(inputField.getText()));
panel.add(equalButton);
}
private void doCalculation() {
String currentInput = inputField.getText();
if (!currentInput.isEmpty()) {
int index = Integer.parseInt(currentInput.split("\\+|-|*|/")[currentInput.length() - 1]) - 48;
inputField.setText(currentInput + buttons[index].getText());
}
}
private void performFinalCalculation(String expression) {
try {
double result = eval(expression);
inputField.setText(String.format("%.2f", result));
} catch (Exception e) {
inputField.setText("Invalid input");
}
}
private double eval(String expression) throws Exception {
return Double.parseDouble(new Scanner(expression).useDelimiter("\\+|-|*|/").nextDouble());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}
```
在这个例子中,我们创建了一个JFrame,包含一个文本框显示当前输入,以及按钮对应数字和操作符。点击按钮时,会更新文本框的内容并触发`doCalculation()`函数。当用户点击等于号时,会尝试计算整个表达式,并显示结果。
注意:这个例子仅实现了基本的加减乘除功能,并未处理所有可能的错误情况。在实际应用中,可能需要更复杂的设计和异常处理。
阅读全文