利用java创建一个计算器程序窗口
时间: 2023-09-24 15:11:01 浏览: 91
可以使用Java Swing库创建一个简单的计算器程序窗口。以下是一个示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField displayField;
private JButton[] numberButtons;
private JButton[] operatorButtons;
private JButton clearButton, equalsButton;
private double operand1, operand2;
private String operator;
public Calculator() {
super("Calculator");
displayField = new JTextField(16);
displayField.setEditable(false);
add(displayField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(Integer.toString(i));
numberButtons[i].addActionListener(this);
buttonPanel.add(numberButtons[i]);
}
operatorButtons = new JButton[6];
operatorButtons[0] = new JButton("+");
operatorButtons[1] = new JButton("-");
operatorButtons[2] = new JButton("*");
operatorButtons[3] = new JButton("/");
operatorButtons[4] = new JButton(".");
operatorButtons[5] = new JButton("C");
for (int i = 0; i < 6; i++) {
operatorButtons[i].addActionListener(this);
buttonPanel.add(operatorButtons[i]);
}
add(buttonPanel, BorderLayout.CENTER);
equalsButton = new JButton("=");
equalsButton.addActionListener(this);
clearButton = new JButton("C");
clearButton.addActionListener(this);
JPanel bottomPanel = new JPanel();
bottomPanel.add(clearButton);
bottomPanel.add(equalsButton);
add(bottomPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("+") || command.equals("-") || command.equals("*") || command.equals("/")) {
operand1 = Double.parseDouble(displayField.getText());
operator = command;
displayField.setText("");
} else if (command.equals(".")) {
if (!displayField.getText().contains(".")) {
displayField.setText(displayField.getText() + ".");
}
} else if (command.equals("=")) {
operand2 = Double.parseDouble(displayField.getText());
double result = 0.0;
if (operator.equals("+")) {
result = operand1 + operand2;
} else if (operator.equals("-")) {
result = operand1 - operand2;
} else if (operator.equals("*")) {
result = operand1 * operand2;
} else if (operator.equals("/")) {
result = operand1 / operand2;
}
displayField.setText(Double.toString(result));
} else if (command.equals("C")) {
displayField.setText("");
} else {
displayField.setText(displayField.getText() + command);
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
这个程序创建了一个带有数字、运算符、清除和等于按钮的简单计算器窗口。用户可以按下数字和运算符按钮,然后按下等于按钮以计算结果。
阅读全文