java语言完成基础任务三:设计简易计算器软件 1.使用Java图形界面组件设计软件,界面如满足基本的“加、减、乘、除”等运算要求。
时间: 2023-12-14 11:39:35 浏览: 80
好的,以下是一个简单的Java图形界面计算器的代码实现:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField inputField; // 输入框
private JButton addButton, subButton, mulButton, divButton; // 四则运算按钮
private JButton equalButton, clearButton; // 等号和清除按钮
private double num1, num2, result; // 运算数和结果
private String operator; // 运算符
public Calculator() {
setTitle("简易计算器");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建输入框和按钮
inputField = new JTextField(16);
addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
equalButton = new JButton("=");
clearButton = new JButton("清除");
// 设置按钮监听器
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
divButton.addActionListener(this);
equalButton.addActionListener(this);
clearButton.addActionListener(this);
// 添加组件到容器
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(inputField);
contentPane.add(addButton);
contentPane.add(subButton);
contentPane.add(mulButton);
contentPane.add(divButton);
contentPane.add(equalButton);
contentPane.add(clearButton);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
// 获取输入框中的文本
String text = inputField.getText();
// 处理清除按钮事件
if (event.getSource() == clearButton) {
inputField.setText("");
num1 = num2 = result = 0.0;
operator = null;
return;
}
// 处理数字按钮事件
try {
double num = Double.parseDouble(text);
if (operator == null) {
num1 = num;
} else {
num2 = num;
}
} catch (NumberFormatException e) {
// 忽略非法数字输入
return;
}
// 处理四则运算按钮事件
if (event.getSource() == addButton) {
operator = "+";
} else if (event.getSource() == subButton) {
operator = "-";
} else if (event.getSource() == mulButton) {
operator = "*";
} else if (event.getSource() == divButton) {
operator = "/";
}
// 处理等号按钮事件
if (event.getSource() == equalButton) {
if (operator == null) {
return;
}
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0.0) {
JOptionPane.showMessageDialog(this, "除数不能为零", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
result = num1 / num2;
break;
}
inputField.setText(Double.toString(result));
num1 = result;
num2 = 0.0;
operator = null;
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这段代码使用了Java的AWT和Swing图形界面组件库,实现了一个简单的计算器界面,并且支持加、减、乘、除等四则运算。
阅读全文