用Java实现以下功能:,制作图像简易计算器只包含加减乘除以及“MC”键实现清除右侧的显示内容。通过鼠标点击实现运算
时间: 2024-03-17 08:41:39 浏览: 153
好的,下面是Java实现图像简易计算器的代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ImageCalculator extends JFrame implements ActionListener {
private JTextField resultField; // 显示结果的文本框
private JButton addButton; // 加法按钮
private JButton minusButton; // 减法按钮
private JButton multiplyButton; // 乘法按钮
private JButton divideButton; // 除法按钮
private JButton clearButton; // 清除按钮
private double result; // 计算结果
private String operator; // 当前运算符
public ImageCalculator() {
super("图像简易计算器"); // 设置窗口标题
// 初始化组件
resultField = new JTextField("0", 20);
resultField.setEditable(false);
addButton = new JButton("+");
minusButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
clearButton = new JButton("MC");
// 添加事件监听器
addButton.addActionListener(this);
minusButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
clearButton.addActionListener(this);
// 构造界面布局
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 1));
panel.add(resultField);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 5));
buttonPanel.add(addButton);
buttonPanel.add(minusButton);
buttonPanel.add(multiplyButton);
buttonPanel.add(divideButton);
buttonPanel.add(clearButton);
panel.add(buttonPanel);
this.add(panel);
// 设置窗口属性
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
// 处理按钮点击事件
public void actionPerformed(ActionEvent e) {
String text = e.getActionCommand();
if (text.equals("+")) {
operator = "+";
result = Double.parseDouble(resultField.getText());
resultField.setText("0");
} else if (text.equals("-")) {
operator = "-";
result = Double.parseDouble(resultField.getText());
resultField.setText("0");
} else if (text.equals("*")) {
operator = "*";
result = Double.parseDouble(resultField.getText());
resultField.setText("0");
} else if (text.equals("/")) {
operator = "/";
result = Double.parseDouble(resultField.getText());
resultField.setText("0");
} else if (text.equals("MC")) {
resultField.setText("0");
} else {
// 数字按钮
String input = text;
if (resultField.getText().equals("0")) {
resultField.setText(input);
} else {
resultField.setText(resultField.getText() + input);
}
}
// 计算结果
if (operator != null && !operator.equals("")) {
double operand = Double.parseDouble(resultField.getText());
if (operator.equals("+")) {
result += operand;
} else if (operator.equals("-")) {
result -= operand;
} else if (operator.equals("*")) {
result *= operand;
} else if (operator.equals("/")) {
if (operand == 0) {
resultField.setText("除数不能为0");
} else {
result /= operand;
}
}
// 显示结果
if (!resultField.getText().equals("除数不能为0")) {
resultField.setText(Double.toString(result));
}
operator = "";
}
}
public static void main(String[] args) {
new ImageCalculator();
}
}
```
这个简易计算器只包含加减乘除以及“MC”键实现清除右侧的显示内容,通过鼠标点击实现运算。你可以根据自己的需要进行修改和扩展。
阅读全文