请你帮我用java语言写一个计算器,带有窗口
时间: 2023-11-19 17:05:01 浏览: 88
用java写的一个计算器
好的,下面是一个简单的 Java 计算器程序,带有窗口界面,可以进行加、减、乘、除四种基本运算:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorGUI extends JFrame implements ActionListener {
private JLabel labelNum1, labelNum2, labelResult;
private JTextField textFieldNum1, textFieldNum2, textFieldResult;
private JButton buttonAdd, buttonSubtract, buttonMultiply, buttonDivide;
public CalculatorGUI() {
setTitle("计算器");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
labelNum1 = new JLabel("第一个数字:");
labelNum2 = new JLabel("第二个数字:");
labelResult = new JLabel("计算结果:");
textFieldNum1 = new JTextField(10);
textFieldNum2 = new JTextField(10);
textFieldResult = new JTextField(10);
textFieldResult.setEditable(false);
buttonAdd = new JButton("+");
buttonSubtract = new JButton("-");
buttonMultiply = new JButton("*");
buttonDivide = new JButton("/");
buttonAdd.addActionListener(this);
buttonSubtract.addActionListener(this);
buttonMultiply.addActionListener(this);
buttonDivide.addActionListener(this);
JPanel panelInput = new JPanel(new GridLayout(2, 2));
panelInput.add(labelNum1);
panelInput.add(textFieldNum1);
panelInput.add(labelNum2);
panelInput.add(textFieldNum2);
JPanel panelButtons = new JPanel(new GridLayout(1, 4));
panelButtons.add(buttonAdd);
panelButtons.add(buttonSubtract);
panelButtons.add(buttonMultiply);
panelButtons.add(buttonDivide);
JPanel panelOutput = new JPanel(new GridLayout(1, 2));
panelOutput.add(labelResult);
panelOutput.add(textFieldResult);
JPanel panelMain = new JPanel(new GridLayout(3, 1));
panelMain.add(panelInput);
panelMain.add(panelButtons);
panelMain.add(panelOutput);
add(panelMain);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(textFieldNum1.getText());
double num2 = Double.parseDouble(textFieldNum2.getText());
double result = 0.0;
if (e.getSource() == buttonAdd) {
result = num1 + num2;
} else if (e.getSource() == buttonSubtract) {
result = num1 - num2;
} else if (e.getSource() == buttonMultiply) {
result = num1 * num2;
} else if (e.getSource() == buttonDivide) {
if (num2 == 0) {
JOptionPane.showMessageDialog(null, "除数不能为0", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
result = num1 / num2;
}
textFieldResult.setText(String.valueOf(result));
}
public static void main(String[] args) {
new CalculatorGUI();
}
}
```
运行程序后,它会打开一个窗口界面,在界面中输入两个数字和一个运算符,然后点击计算按钮,输出计算结果。如果除数为0,则会弹出一个错误提示窗口。
阅读全文