用java做一个计算器窗口
时间: 2024-01-12 18:02:34 浏览: 78
利用java做一个计算器
好的,以下是一个简单的计算器窗口的Java代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame {
private JTextField displayField;
private double num1, num2, result;
private String operator;
public Calculator() {
super("Calculator");
// 创建显示文本框
displayField = new JTextField(10);
displayField.setEditable(false);
add(displayField, BorderLayout.NORTH);
// 创建数字按钮
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(new ButtonListener());
buttonPanel.add(button);
}
add(buttonPanel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String buttonLabel = e.getActionCommand();
// 处理数字输入
if (buttonLabel.matches("[0-9.]")) {
displayField.setText(displayField.getText() + buttonLabel);
}
// 处理运算符输入
else if (buttonLabel.matches("[/*\\-+]=?")) {
if (operator == null) {
num1 = Double.parseDouble(displayField.getText());
operator = buttonLabel;
displayField.setText("");
} else {
num2 = Double.parseDouble(displayField.getText());
result = calculate(num1, num2, operator);
operator = buttonLabel;
num1 = result;
displayField.setText(String.valueOf(result));
}
}
}
private double calculate(double num1, double num2, String operator) {
switch (operator) {
case "/":
return num1 / num2;
case "*":
return num1 * num2;
case "-":
return num1 - num2;
case "+":
return num1 + num2;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个计算器窗口包括一个文本框和数字按钮和运算符按钮,可以进行加、减、乘、除以及小数点的输入和计算。当用户输入数字和运算符时,程序会根据输入的内容进行相应的计算,并在文本框中显示结果。
阅读全文