java构造窗口,动态实现加减乘除运算
时间: 2023-07-12 10:10:23 浏览: 109
好的,以下是一个使用Java Swing构建简单计算器窗口的示例代码,包括实现加减乘除四个运算的功能。
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField number1, number2, result;
private JButton addBtn, subtractBtn, multiplyBtn, divideBtn, clearBtn;
public static void main(String[] args) {
new Calculator();
}
public Calculator() {
super("Calculator");
JPanel inputPanel = new JPanel(new GridLayout(2, 2));
number1 = new JTextField();
number2 = new JTextField();
inputPanel.add(new JLabel("Number 1:"));
inputPanel.add(number1);
inputPanel.add(new JLabel("Number 2:"));
inputPanel.add(number2);
JPanel buttonPanel = new JPanel(new GridLayout(1, 5));
addBtn = new JButton("+");
subtractBtn = new JButton("-");
multiplyBtn = new JButton("*");
divideBtn = new JButton("/");
clearBtn = new JButton("C");
addBtn.addActionListener(this);
subtractBtn.addActionListener(this);
multiplyBtn.addActionListener(this);
divideBtn.addActionListener(this);
clearBtn.addActionListener(this);
buttonPanel.add(addBtn);
buttonPanel.add(subtractBtn);
buttonPanel.add(multiplyBtn);
buttonPanel.add(divideBtn);
buttonPanel.add(clearBtn);
JPanel resultPanel = new JPanel(new GridLayout(1, 2));
result = new JTextField();
result.setEditable(false);
resultPanel.add(new JLabel("Result:"));
resultPanel.add(result);
setLayout(new BorderLayout());
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
add(resultPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String str1 = number1.getText();
String str2 = number2.getText();
double n1 = Double.parseDouble(str1);
double n2 = Double.parseDouble(str2);
double res = 0;
if (e.getSource() == addBtn) {
res = n1 + n2;
} else if (e.getSource() == subtractBtn) {
res = n1 - n2;
} else if (e.getSource() == multiplyBtn) {
res = n1 * n2;
} else if (e.getSource() == divideBtn) {
res = n1 / n2;
} else if (e.getSource() == clearBtn) {
number1.setText("");
number2.setText("");
result.setText("");
return;
}
result.setText(String.valueOf(res));
}
}
```
这段代码会创建一个简单的计算器窗口,用户可以在文本框中输入两个数字,并通过点击按钮进行加减乘除四种运算。结果将显示在另一个文本框中。
阅读全文