java编写一个计算器带窗口
时间: 2024-01-11 15:19:47 浏览: 89
以下是Java编写一个带窗口的计算器的示例代码:
```java
import java.awt.*;
import java.awt.event.*;import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField firstNumField, secondNumField, resultField;
private JButton addButton, subtractButton, multiplyButton, divideButton;
public Calculator() {
super("计算器");
setLayout(new FlowLayout());
// 添加第一个文本框
firstNumField = new JTextField(10);
add(firstNumField);
// 添加加号按钮
addButton = new JButton("+");
addButton.addActionListener(this);
add(addButton);
// 添加减号按钮
subtractButton = new JButton("-");
subtractButton.addActionListener(this);
add(subtractButton);
// 添加乘号按钮
multiplyButton = new JButton("*");
multiplyButton.addActionListener(this);
add(multiplyButton);
// 添加除号按钮
divideButton = new JButton("/");
divideButton.addActionListener(this);
add(divideButton);
// 添加第二个文本框
secondNumField = new JTextField(10);
add(secondNumField);
// 添加等号按钮
JButton equalsButton = new JButton("=");
equalsButton.addActionListener(this);
add(equalsButton);
// 添加结果文本框
resultField = new JTextField(10);
resultField.setEditable(false);
add(resultField);
setSize(200, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double firstNum = Double.parseDouble(firstNumField.getText());
double secondNum = Double.parseDouble(secondNumField.getText());
double result = 0;
if (e.getSource() == addButton) {
result = firstNum + secondNum;
} else if (e.getSource() == subtractButton) {
result = firstNum - secondNum;
} else if (e.getSource() == multiplyButton) {
result = firstNum * secondNum;
} else if (e.getSource() == divideButton) {
result = firstNum / secondNum;
}
resultField.setText(Double.toString(result));
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
阅读全文