用java实现一个图形用户界面类型的简单计算器
时间: 2023-12-09 14:04:02 浏览: 75
好的,以下是一个使用 Java Swing 实现的简单计算器 GUI:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorGUI extends JFrame implements ActionListener {
private JTextField num1Field, num2Field, resultField;
private JButton addButton, subtractButton, multiplyButton, divideButton;
public CalculatorGUI() {
setTitle("简单计算器");
setSize(300, 200);
setLocationRelativeTo(null);
// 创建输入框和标签
JLabel num1Label = new JLabel("第一个数");
num1Field = new JTextField(10);
JLabel num2Label = new JLabel("第二个数");
num2Field = new JTextField(10);
JLabel resultLabel = new JLabel("结果");
resultField = new JTextField(10);
resultField.setEditable(false);
// 创建按钮
addButton = new JButton("+");
addButton.addActionListener(this);
subtractButton = new JButton("-");
subtractButton.addActionListener(this);
multiplyButton = new JButton("*");
multiplyButton.addActionListener(this);
divideButton = new JButton("/");
divideButton.addActionListener(this);
// 创建面板
JPanel inputPanel = new JPanel(new GridLayout(3, 2));
inputPanel.add(num1Label);
inputPanel.add(num1Field);
inputPanel.add(num2Label);
inputPanel.add(num2Field);
inputPanel.add(resultLabel);
inputPanel.add(resultField);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(addButton);
buttonPanel.add(subtractButton);
buttonPanel.add(multiplyButton);
buttonPanel.add(divideButton);
// 添加面板
setLayout(new BorderLayout());
add(inputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double result = num1 + num2;
resultField.setText(String.valueOf(result));
} else if (e.getSource() == subtractButton) {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double result = num1 - num2;
resultField.setText(String.valueOf(result));
} else if (e.getSource() == multiplyButton) {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double result = num1 * num2;
resultField.setText(String.valueOf(result));
} else if (e.getSource() == divideButton) {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
if (num2 == 0) {
resultField.setText("除数不能为0!");
} else {
double result = num1 / num2;
resultField.setText(String.valueOf(result));
}
}
}
public static void main(String[] args) {
CalculatorGUI calculator = new CalculatorGUI();
calculator.setVisible(true);
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
这个计算器 GUI 包含两个文本框用于输入数值,一个文本框用于显示结果,以及四个按钮用于进行加减乘除四则运算。当用户点击某个按钮时,程序会根据对应的运算符计算结果并显示在结果文本框中。
阅读全文