用java创建一个能够计算加减法的计算器窗体
时间: 2024-03-25 19:41:13 浏览: 65
好的,以下是一个简单的Java计算器窗体,可以进行加减运算:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorUI extends JFrame implements ActionListener {
private JTextField num1Field;
private JTextField num2Field;
private JTextField resultField;
public CalculatorUI() {
super("加减计算器");
setLayout(new FlowLayout());
JLabel num1Label = new JLabel("第一个数:");
num1Field = new JTextField(10);
add(num1Label);
add(num1Field);
JLabel num2Label = new JLabel("第二个数:");
num2Field = new JTextField(10);
add(num2Label);
add(num2Field);
JLabel resultLabel = new JLabel("计算结果:");
resultField = new JTextField(10);
resultField.setEditable(false);
add(resultLabel);
add(resultField);
JButton addButton = new JButton("+");
addButton.addActionListener(this);
add(addButton);
JButton subButton = new JButton("-");
subButton.addActionListener(this);
add(subButton);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(250, 150);
setLocationRelativeTo(null); // 居中显示
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
if (e.getActionCommand().equals("+")) {
resultField.setText(Double.toString(num1 + num2));
} else if (e.getActionCommand().equals("-")) {
resultField.setText(Double.toString(num1 - num2));
}
}
public static void main(String[] args) {
new CalculatorUI();
}
}
```
你可以运行该程序,会弹出一个窗口,输入两个数和点击加号或减号按钮,程序会返回计算结果。
阅读全文