通过java swing编写一个计算器
时间: 2023-12-08 10:04:29 浏览: 88
好的,下面是一个简单的 Java Swing 计算器实现,包括加减乘除四则运算:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField num1Field, num2Field, resultField;
private JButton addButton, subButton, mulButton, divButton;
public Calculator() {
super("Calculator");
setLayout(new GridLayout(4, 2));
JLabel num1Label = new JLabel("Number 1:");
num1Field = new JTextField(10);
JLabel num2Label = new JLabel("Number 2:");
num2Field = new JTextField(10);
JLabel resultLabel = new JLabel("Result:");
resultField = new JTextField(10);
resultField.setEditable(false);
addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
divButton.addActionListener(this);
add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(resultLabel);
add(resultField);
add(addButton);
add(subButton);
add(mulButton);
add(divButton);
setSize(300, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double result = 0;
if (e.getSource() == addButton) {
result = num1 + num2;
} else if (e.getSource() == subButton) {
result = num1 - num2;
} else if (e.getSource() == mulButton) {
result = num1 * num2;
} else if (e.getSource() == divButton) {
result = num1 / num2;
}
resultField.setText(Double.toString(result));
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
该计算器界面包含两个文本框和四个按钮,用户可以输入两个数字并选择加减乘除四个运算符。结果将显示在第三个文本框中。运算过程在 `actionPerformed` 方法中实现。
阅读全文