设计一个程序,用两个JTextField 输入x、y,并利用数学函数计算xy,将结果显示在一个JLabel 中。
时间: 2024-05-03 16:20:24 浏览: 16
好的,这个问题是一个编程问题,可以回答。以下是Java语言的示例代码:
```java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xField, yField;
private JLabel resultLabel;
public Calculator() {
frame = new JFrame("Calculator");
frame.setLayout(null);
JLabel xLabel = new JLabel("x:");
xLabel.setBounds(50, 50, 30, 25);
frame.add(xLabel);
xField = new JTextField();
xField.setBounds(80, 50, 100, 25);
frame.add(xField);
JLabel yLabel = new JLabel("y:");
yLabel.setBounds(50, 80, 30, 25);
frame.add(yLabel);
yField = new JTextField();
yField.setBounds(80, 80, 100, 25);
frame.add(yField);
JButton calculateButton = new JButton("Calculate");
calculateButton.setBounds(200, 50, 100, 55);
calculateButton.addActionListener(this);
frame.add(calculateButton);
JLabel resultTitle = new JLabel("Result:");
resultTitle.setBounds(50, 120, 50, 25);
frame.add(resultTitle);
resultLabel = new JLabel("Please input x and y.");
resultLabel.setBounds(100, 120, 200, 25);
frame.add(resultLabel);
frame.setSize(350, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
double x = Double.parseDouble(xField.getText());
double y = Double.parseDouble(yField.getText());
double result = Math.pow(x, y);
resultLabel.setText(String.format("%.2f ^ %.2f = %.2f", x, y, result));
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个程序创建了一个简单的计算器界面,包括两个文本框和一个标签。用户输入x和y之后,点击“Calculate”按钮,程序会将x和y进行乘方运算,然后将结果显示在标签中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)