写一个Java gui计算器实现两个数之间的加减乘除,用户输入格式不正确时可以给出tishixinxi
时间: 2024-02-06 20:09:33 浏览: 75
好的,以下是一个简单的Java GUI计算器实现:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalculatorGUI implements ActionListener {
private JFrame frame;
private JPanel panel;
private JTextField numField1, numField2, resultField;
private JButton addButton, subtractButton, multiplyButton, divideButton;
public CalculatorGUI() {
// 创建 JFrame 和 JPanel
frame = new JFrame("Calculator");
panel = new JPanel(new GridLayout(4, 2));
// 创建文本框和按钮
numField1 = new JTextField();
numField2 = new JTextField();
resultField = new JTextField();
resultField.setEditable(false);
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
// 将文本框和按钮添加到面板中
panel.add(new JLabel("Number 1:"));
panel.add(numField1);
panel.add(new JLabel("Number 2:"));
panel.add(numField2);
panel.add(new JLabel("Result:"));
panel.add(resultField);
panel.add(addButton);
panel.add(subtractButton);
panel.add(multiplyButton);
panel.add(divideButton);
// 添加监听器
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
// 设置 JFrame 属性并显示窗口
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
// 实现 ActionListener 接口中的 actionPerformed 方法
public void actionPerformed(ActionEvent e) {
// 获取输入的两个数
double num1, num2;
try {
num1 = Double.parseDouble(numField1.getText());
num2 = Double.parseDouble(numField2.getText());
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "请输入正确的数字!");
return;
}
// 根据按钮的标签执行相应的操作
String operation = e.getActionCommand();
double result = 0;
switch (operation) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
JOptionPane.showMessageDialog(frame, "除数不能为零!");
return;
}
result = num1 / num2;
break;
}
// 显示结果
resultField.setText(String.valueOf(result));
}
public static void main(String[] args) {
CalculatorGUI calculator = new CalculatorGUI();
}
}
```
这个计算器可以实现两个数之间的加减乘除运算,并且当用户输入不正确时会弹出提示框。
阅读全文