用java写一个星空代码
时间: 2024-05-11 07:14:57 浏览: 14
这里是一个简单的Java代码,用于生成随机星空效果:
```
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class StarryNight extends JPanel {
private static final int NUM_STARS = 500;
private static final int MIN_STAR_SIZE = 1;
private static final int MAX_STAR_SIZE = 4;
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 600;
private Random random;
private int[] starX;
private int[] starY;
private int[] starSize;
public StarryNight() {
random = new Random();
starX = new int[NUM_STARS];
starY = new int[NUM_STARS];
starSize = new int[NUM_STARS];
for (int i = 0; i < NUM_STARS; i++) {
starX[i] = random.nextInt(WINDOW_WIDTH);
starY[i] = random.nextInt(WINDOW_HEIGHT);
starSize[i] = MIN_STAR_SIZE + random.nextInt(MAX_STAR_SIZE - MIN_STAR_SIZE + 1);
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
setBackground(Color.BLACK);
for (int i = 0; i < NUM_STARS; i++) {
g.setColor(Color.WHITE);
g.fillOval(starX[i], starY[i], starSize[i], starSize[i]);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Starry Night");
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
StarryNight panel = new StarryNight();
frame.add(panel);
frame.setVisible(true);
}
}
```
代码解释:
1. NUM_STARS 定义了星星的数量。
2. MIN_STAR_SIZE 和 MAX_STAR_SIZE 定义了星星的大小范围。
3. WINDOW_WIDTH 和 WINDOW_HEIGHT 定义了窗口的大小。
4. 随机生成 NUM_STARS 个星星的位置和大小。
5. 在 paint 方法中,使用 Graphics 对象画出所有的星星。
6. 在 main 方法中,创建一个 JFrame 对象,并将 StarryNight 对象作为 JPanel 添加到 JFrame 中。最后,使 JFrame 可见。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)