写一个创意javaGUI小程序,要求有代码
时间: 2024-02-22 13:59:25 浏览: 22
好的,这是一个Java GUI小程序,它可以让用户输入一个数值,并计算它的平方、立方和四次方。下面是代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PowerCalculator extends JFrame implements ActionListener {
private JTextField inputField;
private JButton calculateButton;
private JLabel squareLabel;
private JLabel cubeLabel;
private JLabel fourthPowerLabel;
public PowerCalculator() {
setTitle("Power Calculator");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
JLabel inputLabel = new JLabel("Enter a number:");
inputField = new JTextField();
panel.add(inputLabel);
panel.add(inputField);
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
panel.add(calculateButton);
JLabel squareTextLabel = new JLabel("Square:");
squareLabel = new JLabel();
panel.add(squareTextLabel);
panel.add(squareLabel);
JLabel cubeTextLabel = new JLabel("Cube:");
cubeLabel = new JLabel();
panel.add(cubeTextLabel);
panel.add(cubeLabel);
JLabel fourthPowerTextLabel = new JLabel("Fourth Power:");
fourthPowerLabel = new JLabel();
panel.add(fourthPowerTextLabel);
panel.add(fourthPowerLabel);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double num = Double.parseDouble(inputField.getText());
double square = Math.pow(num, 2);
double cube = Math.pow(num, 3);
double fourthPower = Math.pow(num, 4);
squareLabel.setText(String.format("%.2f", square));
cubeLabel.setText(String.format("%.2f", cube));
fourthPowerLabel.setText(String.format("%.2f", fourthPower));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Please enter a valid number.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
new PowerCalculator();
}
}
```
这个程序创建了一个窗口,里面有一个文本框、一个按钮和三个标签。当用户输入一个数值并点击按钮时,程序会计算这个数值的平方、立方和四次方,并将结果显示在对应的标签上。如果用户输入的不是一个数值,程序会弹出一个错误提示框。这个程序可以帮助你练习使用Java GUI编程和处理用户输入。
相关推荐
![](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)