设计一个简单的四则运算工具,有一个标题为“计算”的窗口,窗口布局为FlowLayout。设计四个按钮,分别命名为“加”、“减”、“乘”、“除”,此外,窗口中还有三个文本框,前两个可以输入数字。单击
时间: 2023-10-02 16:07:56 浏览: 82
四个按钮中的任意一个,程序将根据所选的运算符对输入的两个数字进行相应的计算,并将结果显示在第三个文本框中。
代码示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JLabel title;
private JTextField num1, num2, result;
private JButton add, subtract, multiply, divide;
public Calculator() {
setTitle("计算");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
title = new JLabel("四则运算");
add(title);
num1 = new JTextField(10);
add(num1);
num2 = new JTextField(10);
add(num2);
result = new JTextField(10);
result.setEditable(false);
add(result);
add = new JButton("加");
add.addActionListener(this);
add(add);
subtract = new JButton("减");
subtract.addActionListener(this);
add(subtract);
multiply = new JButton("乘");
multiply.addActionListener(this);
add(multiply);
divide = new JButton("除");
divide.addActionListener(this);
add(divide);
pack();
setVisible(true);
}
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) {
if (n2 == 0) {
JOptionPane.showMessageDialog(this, "除数不能为零!");
} else {
res = n1 / n2;
}
}
result.setText(String.valueOf(res));
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
在这个示例中,我们使用了Java Swing的JFrame、JLabel、JTextField和JButton组件来创建一个简单的计算器。我们还实现了ActionListener接口来处理按钮的单击事件,并根据所选的运算符对输入的两个数字进行运算。最后,我们使用JOptionPane来显示除数为零的错误提示。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)