用JAVA写一个有窗体的计算器
时间: 2023-11-18 10:06:27 浏览: 100
计算器窗体
4星 · 用户满意度95%
以下是一个简单的 Java 计算器程序,带有 GUI 界面:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
private JButton[] buttons;
private String[] buttonTexts = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
private double num1 = 0, num2 = 0;
private String operator = "";
private boolean isOperatorClicked = false;
public Calculator() {
setTitle("计算器");
setSize(300, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField = new JTextField();
textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT);
add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel(new GridLayout(4, 4));
buttons = new JButton[16];
for (int i = 0; i < 16; i++) {
buttons[i] = new JButton(buttonTexts[i]);
buttons[i].addActionListener(this);
panel.add(buttons[i]);
}
add(panel, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String buttonText = e.getActionCommand();
if (buttonText.equals("C")) {
textField.setText("");
num1 = 0;
num2 = 0;
operator = "";
isOperatorClicked = false;
} else if (buttonText.equals("=")) {
num2 = Double.parseDouble(textField.getText());
double result = 0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
textField.setText(String.valueOf(result));
num1 = result;
num2 = 0;
operator = "";
isOperatorClicked = false;
} else if (buttonText.equals("+") || buttonText.equals("-") || buttonText.equals("*") || buttonText.equals("/")) {
if (isOperatorClicked) {
num1 = Double.parseDouble(textField.getText());
} else {
num1 = Double.parseDouble(textField.getText());
textField.setText("");
}
operator = buttonText;
isOperatorClicked = true;
} else {
textField.setText(textField.getText() + buttonText);
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
运行程序后,即可看到一个带有数字和运算符按钮的窗口,可以进行简单的四则运算。
阅读全文