1、设计一个程序,用两个文本框输入X、Y,用按钮完成相应算术操作,将结果显示在一个标签中。用Java语言
时间: 2024-02-06 21:10:28 浏览: 79
以下是一个简单的 Java GUI 界面程序,可以实现两个文本框输入 X 和 Y,通过按钮完成相应算术操作,并将结果显示在一个标签中:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ArithmeticsGUI extends JFrame implements ActionListener {
private JTextField xTextField, yTextField;
private JLabel resultLabel;
public ArithmeticsGUI() {
super("Arithmetics Calculator");
// 设置窗口大小和布局
setSize(400, 150);
setLayout(new GridLayout(3, 2));
// 添加 X 和 Y 文本框
add(new JLabel("X:"));
xTextField = new JTextField(10);
add(xTextField);
add(new JLabel("Y:"));
yTextField = new JTextField(10);
add(yTextField);
// 添加加减乘除按钮
JButton addButton = new JButton("+");
addButton.addActionListener(this);
add(addButton);
JButton subButton = new JButton("-");
subButton.addActionListener(this);
add(subButton);
JButton mulButton = new JButton("*");
mulButton.addActionListener(this);
add(mulButton);
JButton divButton = new JButton("/");
divButton.addActionListener(this);
add(divButton);
// 添加结果标签
add(new JLabel("Result:"));
resultLabel = new JLabel("");
add(resultLabel);
}
public void actionPerformed(ActionEvent e) {
// 获取 X 和 Y 数值
double x = Double.parseDouble(xTextField.getText());
double y = Double.parseDouble(yTextField.getText());
// 根据按钮的不同操作进行相应算术操作
if (e.getActionCommand().equals("+")) {
resultLabel.setText(Double.toString(x + y));
} else if (e.getActionCommand().equals("-")) {
resultLabel.setText(Double.toString(x - y));
} else if (e.getActionCommand().equals("*")) {
resultLabel.setText(Double.toString(x * y));
} else if (e.getActionCommand().equals("/")) {
resultLabel.setText(Double.toString(x / y));
}
}
public static void main(String[] args) {
// 创建 GUI 界面
ArithmeticsGUI frame = new ArithmeticsGUI();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
该程序中,我们创建了一个 `ArithmeticsGUI` 类,继承自 `JFrame` 类,实现了 `ActionListener` 接口。在构造函数中,我们设置了窗口的大小和布局,并添加了 X 和 Y 的文本框、加减乘除按钮以及结果标签。当用户点击按钮时,我们通过 `ActionEvent` 对象获取按钮的操作命令,然后根据不同的操作命令进行相应的算术操作,并将结果显示在结果标签中。在 `main` 函数中,我们创建了 `ArithmeticsGUI` 对象,设置窗口可见性并设置关闭模式。
阅读全文
相关推荐
















