使用java程序在应用程序窗体中安排两个文本框分别用来输入两个整数,两个按钮分别为“”、“/”,一个结果标签。点击按纽“”将两文本框的数据做乘法运算;点击按钮“/”做除法运算;点击“清除”清空两个文本框内容,将运算式与结果显示在标签中。
时间: 2023-10-08 16:12:16 浏览: 73
好的,我可以为您提供一份Java代码,实现您的需求。请参考下面的代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator implements ActionListener {
private JFrame frame;
private JLabel label1, label2, resultLabel;
private JTextField textField1, textField2;
private JButton multiplyButton, divideButton, clearButton;
public Calculator() {
frame = new JFrame("Calculator");
frame.setLayout(new GridLayout(4, 2));
label1 = new JLabel("Num1:");
frame.add(label1);
textField1 = new JTextField();
frame.add(textField1);
label2 = new JLabel("Num2:");
frame.add(label2);
textField2 = new JTextField();
frame.add(textField2);
multiplyButton = new JButton("*");
multiplyButton.addActionListener(this);
frame.add(multiplyButton);
divideButton = new JButton("/");
divideButton.addActionListener(this);
frame.add(divideButton);
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
frame.add(clearButton);
resultLabel = new JLabel("Result:");
frame.add(resultLabel);
frame.setSize(400, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == multiplyButton) {
int num1 = Integer.parseInt(textField1.getText());
int num2 = Integer.parseInt(textField2.getText());
int result = num1 * num2;
resultLabel.setText("Result: " + result);
} else if (e.getSource() == divideButton) {
int num1 = Integer.parseInt(textField1.getText());
int num2 = Integer.parseInt(textField2.getText());
if (num2 == 0) {
resultLabel.setText("Result: Error");
} else {
double result = (double) num1 / num2;
resultLabel.setText("Result: " + result);
}
} else if (e.getSource() == clearButton) {
textField1.setText("");
textField2.setText("");
resultLabel.setText("Result:");
}
}
}
```
这段代码实现了一个简单的计算器,可以进行乘法和除法运算,同时还有一个清除按钮。您可以将这段代码复制到您的Java IDE中运行,也可以根据您的需求进行修改。希望对您有所帮助!
阅读全文