设计一个程序,用两个JTextField 输入x、y,并利用数学函数计算xy,将结果显示在一个JLabel 中。
时间: 2024-05-03 08:20:24 浏览: 15
好的,这是一个很简单的问题。以下是代码实现:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener {
private JLabel resultLabel;
private JTextField xField, yField;
private JButton calcButton;
public Main() {
setTitle("计算xy");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
JLabel xLabel = new JLabel("X: ");
xField = new JTextField();
panel.add(xLabel);
panel.add(xField);
JLabel yLabel = new JLabel("Y: ");
yField = new JTextField();
panel.add(yLabel);
panel.add(yField);
calcButton = new JButton("计算");
calcButton.addActionListener(this);
panel.add(new JLabel());
panel.add(calcButton);
resultLabel = new JLabel("结果: ");
resultLabel.setHorizontalAlignment(JLabel.CENTER);
resultLabel.setFont(new Font("宋体", Font.BOLD, 18));
add(panel, BorderLayout.CENTER);
add(resultLabel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == calcButton) {
try {
double x = Double.parseDouble(xField.getText());
double y = Double.parseDouble(yField.getText());
double result = Math.pow(x, y);
resultLabel.setText("结果: " + result);
} catch (Exception ex) {
resultLabel.setText("输入有误,请重新输入。");
}
}
}
public static void main(String[] args) {
new Main();
}
}
```
上述代码使用了Java Swing库,实现了一个简单的GUI应用程序,可以输入两个数字x和y,然后计算xy的值并在结果标签中显示。如果输入有误,会在结果标签中显示错误信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)