java窗体简易计算器加减乘除
时间: 2023-07-01 09:27:03 浏览: 94
以下是一个简易的 Java 窗体计算器,支持加减乘除四则运算:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField tfNum1, tfNum2, tfResult;
private JButton btnAdd, btnSub, btnMul, btnDiv;
public Calculator() {
super("Calculator");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
JLabel lblNum1 = new JLabel("Number 1:");
tfNum1 = new JTextField(10);
add(lblNum1);
add(tfNum1);
JLabel lblNum2 = new JLabel("Number 2:");
tfNum2 = new JTextField(10);
add(lblNum2);
add(tfNum2);
JLabel lblResult = new JLabel("Result:");
tfResult = new JTextField(10);
tfResult.setEditable(false);
add(lblResult);
add(tfResult);
btnAdd = new JButton("Add");
add(btnAdd);
btnAdd.addActionListener(this);
btnSub = new JButton("Subtract");
add(btnSub);
btnSub.addActionListener(this);
btnMul = new JButton("Multiply");
add(btnMul);
btnMul.addActionListener(this);
btnDiv = new JButton("Divide");
add(btnDiv);
btnDiv.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(tfNum1.getText());
double num2 = Double.parseDouble(tfNum2.getText());
double result = 0;
if (e.getSource() == btnAdd) {
result = num1 + num2;
} else if (e.getSource() == btnSub) {
result = num1 - num2;
} else if (e.getSource() == btnMul) {
result = num1 * num2;
} else if (e.getSource() == btnDiv) {
result = num1 / num2;
}
tfResult.setText(Double.toString(result));
}
public static void main(String[] args) {
new Calculator();
}
}
```
该计算器使用了 Java 的 Swing GUI 库来创建窗体界面,包含两个文本框用于输入数字,一个文本框用于显示结果,以及四个按钮用于进行四则运算。在点击按钮后,通过 `ActionListener` 接口中的 `actionPerformed` 方法来计算并显示结果。
阅读全文