利用JAVA编写一个简单的单选窗口计算器,要求数字通过点击得到,运算符也是通过点击选择
时间: 2023-10-25 19:07:48 浏览: 165
基于java实现简单计算器
以下是一个简单的单选窗口计算器的JAVA代码,运用了Swing库:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField num1, num2, result;
private JButton add, subtract, multiply, divide;
public Calculator() {
setTitle("Calculator");
setSize(400, 180);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
num1 = new JTextField();
num2 = new JTextField();
result = new JTextField();
result.setEditable(false);
add = new JButton("+");
subtract = new JButton("-");
multiply = new JButton("*");
divide = new JButton("/");
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
add(new JLabel("Num1:"));
add(num1);
add(new JLabel("Num2:"));
add(num2);
add(new JLabel("Result:"));
add(result);
add(add);
add(subtract);
add(multiply);
add(divide);
}
public void actionPerformed(ActionEvent e) {
double n1 = Double.parseDouble(num1.getText());
double n2 = Double.parseDouble(num2.getText());
double res = 0;
if (e.getSource() == add) {
res = n1 + n2;
} else if (e.getSource() == subtract) {
res = n1 - n2;
} else if (e.getSource() == multiply) {
res = n1 * n2;
} else if (e.getSource() == divide) {
res = n1 / n2;
}
result.setText(Double.toString(res));
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.setVisible(true);
}
}
```
这个计算器界面包括两个文本框用于输入数字,一个文本框用于显示结果,以及四个按钮用于选择运算符。每个按钮都绑定了一个事件监听器,点击按钮后会根据选择的运算符计算结果并显示在结果文本框中。
阅读全文