java窗体简易计算器
时间: 2023-09-09 07:08:29 浏览: 97
好的,以下是一个简单的Java窗体计算器程序,支持加、减、乘、除四则运算:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField num1Field, num2Field, resultField;
private JButton addButton, subButton, mulButton, divButton;
public Calculator() {
setTitle("简易计算器");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建面板
JPanel panel = new JPanel(new GridLayout(4, 2));
// 创建组件
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("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
// 添加组件到面板
panel.add(num1Label);
panel.add(num1Field);
panel.add(num2Label);
panel.add(num2Field);
panel.add(resultLabel);
panel.add(resultField);
panel.add(addButton);
panel.add(subButton);
panel.add(mulButton);
panel.add(divButton);
// 添加面板到窗体
add(panel);
// 添加事件监听器
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
divButton.addActionListener(this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double result = 0;
if(e.getSource() == addButton) {
result = num1 + num2;
} else if(e.getSource() == subButton) {
result = num1 - num2;
} else if(e.getSource() == mulButton) {
result = num1 * num2;
} else if(e.getSource() == divButton) {
if(num2 == 0) {
JOptionPane.showMessageDialog(this, "除数不能为0!", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
result = num1 / num2;
}
resultField.setText(String.valueOf(result));
}
public static void main(String[] args) {
new Calculator();
}
}
```
你可以根据需要对代码进行调整和修改,比如添加更多的运算符、增加输入检查等。
阅读全文