java设计一个计算器窗口,尝试完成该计算器窗口的代码
时间: 2023-10-31 15:10:54 浏览: 125
好的,以下是一个简单的计算器窗口的Java代码示例:
```java
import javax.swing.*;
import java.awt.*;
public class Calculator extends JFrame {
private JTextField textField;
private JButton[] buttons;
private String[] buttonLabels = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", ".", "=", "/"
};
private double result = 0;
private String operator = "";
private boolean startOfNumber = true;
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
textField = new JTextField(20);
textField.setHorizontalAlignment(JTextField.RIGHT);
textField.setEditable(false);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
buttons = new JButton[buttonLabels.length];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(e -> buttonClicked(e.getActionCommand()));
buttonPanel.add(buttons[i]);
}
add(textField, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
setVisible(true);
}
private void buttonClicked(String label) {
if ("0123456789.".indexOf(label) >= 0) {
if (startOfNumber) {
textField.setText(label);
} else {
textField.setText(textField.getText() + label);
}
startOfNumber = false;
} else {
if (startOfNumber && "-".equals(label)) {
textField.setText(label);
startOfNumber = false;
} else {
if (!startOfNumber) {
double number = Double.parseDouble(textField.getText());
if ("+".equals(operator)) {
result += number;
} else if ("-".equals(operator)) {
result -= number;
} else if ("*".equals(operator)) {
result *= number;
} else if ("/".equals(operator)) {
result /= number;
} else if ("=".equals(operator)) {
result = number;
}
textField.setText("" + result);
}
operator = label;
startOfNumber = true;
}
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个计算器窗口使用了Java Swing库来创建GUI组件,包括文本框和按钮。每个按钮都有一个标签,当用户单击它时,计算器会执行相应的操作。在此示例中,计算器可以执行加、减、乘、除和等于操作,并且可以输入数字和小数点。
阅读全文