写一个创意javaGUI小程序,要求有代码
时间: 2024-02-22 18:59:24 浏览: 37
好的,我可以给你一个简单的Java GUI小程序,它可以生成随机颜色并将其显示在窗口中。下面是代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RandomColorGenerator extends JFrame implements ActionListener {
private JButton generateButton;
private JLabel colorLabel;
public RandomColorGenerator() {
setTitle("Random Color Generator");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
generateButton = new JButton("Generate");
generateButton.addActionListener(this);
panel.add(generateButton);
colorLabel = new JLabel("Click the button to generate a random color.");
colorLabel.setHorizontalAlignment(JLabel.CENTER);
panel.add(colorLabel);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int r = (int) (Math.random() * 256);
int g = (int) (Math.random() * 256);
int b = (int) (Math.random() * 256);
Color randomColor = new Color(r, g, b);
colorLabel.setForeground(randomColor);
}
public static void main(String[] args) {
new RandomColorGenerator();
}
}
```
这个程序创建了一个窗口,里面有一个按钮和一个标签。当用户点击按钮时,程序会生成一个随机颜色,并将其设置为标签的前景色。这个程序可以帮助你练习使用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)