利用JAVA编写一个简单的单选窗口计算器
时间: 2023-07-30 15:11:44 浏览: 99
用java编写的简单计算器
以下是一个简单的单选窗口计算器的JAVA代码,它可以进行加、减、乘、除四则运算:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField inputField;
private JButton addButton, subtractButton, multiplyButton, divideButton, equalsButton, clearButton;
private double num1, num2;
private char operator;
public Calculator() {
// 设置窗口标题
setTitle("Calculator");
// 设置窗口大小
setSize(300, 300);
// 设置窗口位置
setLocationRelativeTo(null);
// 设置窗口关闭按钮操作
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建输入框
inputField = new JTextField(20);
inputField.setEditable(false);
// 创建按钮
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
equalsButton = new JButton("=");
clearButton = new JButton("C");
// 添加按钮事件监听器
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
equalsButton.addActionListener(this);
clearButton.addActionListener(this);
// 创建面板并添加组件
JPanel panel = new JPanel(new GridLayout(4, 2));
panel.add(inputField);
panel.add(addButton);
panel.add(subtractButton);
panel.add(multiplyButton);
panel.add(divideButton);
panel.add(equalsButton);
panel.add(clearButton);
// 将面板添加到窗口中
add(panel);
// 显示窗口
setVisible(true);
}
// 按钮事件处理方法
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
num1 = Double.parseDouble(inputField.getText());
operator = '+';
inputField.setText("");
} else if (e.getSource() == subtractButton) {
num1 = Double.parseDouble(inputField.getText());
operator = '-';
inputField.setText("");
} else if (e.getSource() == multiplyButton) {
num1 = Double.parseDouble(inputField.getText());
operator = '*';
inputField.setText("");
} else if (e.getSource() == divideButton) {
num1 = Double.parseDouble(inputField.getText());
operator = '/';
inputField.setText("");
} else if (e.getSource() == equalsButton) {
num2 = Double.parseDouble(inputField.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;
}
inputField.setText(Double.toString(result));
} else if (e.getSource() == clearButton) {
inputField.setText("");
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
运行该程序,将会显示一个带有输入框和按钮的窗口,用户可以在输入框中输入数字,并通过单击按钮执行四则运算。
阅读全文