请用Java图形界面的知识,编写一个计算器,要求实现基本的加减乘除运算
时间: 2024-05-07 19:20:10 浏览: 101
以下是一个简单的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, subtractButton, multiplyButton, divideButton, equalsButton, clearButton;
private double num1, num2, result;
private String operator;
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
// 创建文本框和按钮
inputField = new JTextField(20);
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
equalsButton = new JButton("=");
clearButton = new JButton("C");
// 设置按钮的事件监听器
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
equalsButton.addActionListener(this);
clearButton.addActionListener(this);
// 创建面板并添加组件
JPanel panel = new JPanel();
panel.add(inputField);
panel.add(addButton);
panel.add(subtractButton);
panel.add(multiplyButton);
panel.add(divideButton);
panel.add(equalsButton);
panel.add(clearButton);
// 将面板添加到窗口
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// 获取按钮上的文本
String buttonText = e.getActionCommand();
// 根据按钮的文本进行相应的操作
switch (buttonText) {
case "+":
operator = "+";
num1 = Double.parseDouble(inputField.getText());
inputField.setText("");
break;
case "-":
operator = "-";
num1 = Double.parseDouble(inputField.getText());
inputField.setText("");
break;
case "*":
operator = "*";
num1 = Double.parseDouble(inputField.getText());
inputField.setText("");
break;
case "/":
operator = "/";
num1 = Double.parseDouble(inputField.getText());
inputField.setText("");
break;
case "=":
num2 = Double.parseDouble(inputField.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
inputField.setText(Double.toString(result));
break;
case "C":
inputField.setText("");
break;
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
运行程序,即可看到一个简单的计算器界面,可以进行基本的加减乘除运算。
阅读全文