给我用java做一个计算器窗口
时间: 2023-06-27 20:02:57 浏览: 95
好的,以下是一个简单的计算器窗口的Java代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private JButton[] buttons;
private String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
private double result;
private String operator;
public Calculator() {
setTitle("Calculator");
setLayout(new BorderLayout());
display = new JTextField("0");
display.setEditable(false);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
buttons = new JButton[buttonLabels.length];
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
add(buttonPanel, BorderLayout.CENTER);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if (label.equals("C")) {
result = 0;
operator = "";
display.setText("0");
} else if (label.equals("/")) {
result = Double.parseDouble(display.getText());
operator = "/";
display.setText("");
} else if (label.equals("*")) {
result = Double.parseDouble(display.getText());
operator = "*";
display.setText("");
} else if (label.equals("-")) {
result = Double.parseDouble(display.getText());
operator = "-";
display.setText("");
} else if (label.equals("+")) {
result = Double.parseDouble(display.getText());
operator = "+";
display.setText("");
} else if (label.equals("=")) {
double secondOperand = Double.parseDouble(display.getText());
if (operator.equals("/")) {
result /= secondOperand;
} else if (operator.equals("*")) {
result *= secondOperand;
} else if (operator.equals("-")) {
result -= secondOperand;
} else if (operator.equals("+")) {
result += secondOperand;
}
display.setText("" + result);
} else {
String text = display.getText();
if (text.equals("0")) {
display.setText(label);
} else {
display.setText(text + label);
}
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个计算器窗口可以进行基本的加减乘除运算。你可以根据需要进行修改和优化。
阅读全文