使用Java实现以下程序:设计一个程序,用两个文本框输入X、Y,用按钮完成相应算术操作,将结果显示在一个标签
时间: 2024-02-28 08:54:35 浏览: 108
好的,下面是使用Java实现的程序代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ArithmeticCalculator implements ActionListener {
private JFrame frame;
private JTextField textField1, textField2, resultField;
private JButton addButton, subButton, mulButton, divButton;
public ArithmeticCalculator() {
frame = new JFrame("Arithmetic Calculator");
frame.setLayout(new GridLayout(4, 2));
JLabel label1 = new JLabel("X:");
textField1 = new JTextField();
JLabel label2 = new JLabel("Y:");
textField2 = new JTextField();
JLabel label3 = new JLabel("Result:");
resultField = new JTextField();
addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
divButton.addActionListener(this);
frame.add(label1);
frame.add(textField1);
frame.add(label2);
frame.add(textField2);
frame.add(addButton);
frame.add(subButton);
frame.add(mulButton);
frame.add(divButton);
frame.add(label3);
frame.add(resultField);
frame.setSize(300, 150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
String xStr = textField1.getText();
String yStr = textField2.getText();
double x = Double.parseDouble(xStr);
double y = Double.parseDouble(yStr);
if (event.getSource() == addButton) {
double result = x + y;
resultField.setText(Double.toString(result));
} else if (event.getSource() == subButton) {
double result = x - y;
resultField.setText(Double.toString(result));
} else if (event.getSource() == mulButton) {
double result = x * y;
resultField.setText(Double.toString(result));
} else if (event.getSource() == divButton) {
if (y == 0) {
resultField.setText("Error: divide by zero");
} else {
double result = x / y;
resultField.setText(Double.toString(result));
}
}
}
public static void main(String[] args) {
new ArithmeticCalculator();
}
}
```
这个程序使用了Java Swing库来创建GUI界面,为用户提供了两个文本框来输入X和Y,四个按钮完成加、减、乘、除四种算术操作,并将结果显示在一个标签中。用户点击按钮时,程序会获取文本框中的X和Y值,进行相应的算术操作,并将结果显示在标签中。注意,在除法操作中需要处理除数为零的情况。
阅读全文