本案例要求利用Java Swing 图形组件开发一个可以进行简单的四则运算的图形化计算器。
时间: 2024-03-14 14:50:06 浏览: 131
Java计算器应用实现-基础数学运算与Swing界面开发
好的,这是一个简单的四则运算的图形化计算器,可以进行加、减、乘、除四则运算。您可以输入两个数,并选择运算符,点击“计算”按钮,即可得到结果。以下是示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame {
private JTextField num1Field, num2Field, resultField;
private JComboBox<String> operatorBox;
public Calculator() {
super("Calculator");
//设置窗口大小和位置
setSize(300, 200);
setLocationRelativeTo(null);
//设置布局
setLayout(new GridLayout(4, 2));
//添加组件
add(new JLabel("Number 1:"));
num1Field = new JTextField();
add(num1Field);
add(new JLabel("Number 2:"));
num2Field = new JTextField();
add(num2Field);
add(new JLabel("Operator:"));
operatorBox = new JComboBox<>(new String[]{"+", "-", "*", "/"});
add(operatorBox);
add(new JLabel("Result:"));
resultField = new JTextField();
resultField.setEditable(false);
add(resultField);
JButton calcButton = new JButton("Calculate");
//添加计算按钮的事件监听
calcButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取用户输入的数值和运算符
double num1 = Double.parseDouble(num1Field.getText().trim());
double num2 = Double.parseDouble(num2Field.getText().trim());
String operator = (String) operatorBox.getSelectedItem();
//进行四则运算
double result;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
result = 0;
}
//将结果显示到结果文本框中
resultField.setText(Double.toString(result));
}
});
add(calcButton);
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
}
```
运行程序,即可看到界面如下所示:
![calculator](https://user-images.githubusercontent.com/58271566/132969239-08a5d8c8-0e4f-4e4c-9e92-5a1352d1e9d2.png)
阅读全文