用Java编写一个浪漫的烟花
时间: 2023-06-19 18:08:41 浏览: 106
一个美丽的Java烟花代码
以下是一个简单的Java烟花代码示例,可能无法完全实现你所期望的浪漫效果,但可以作为一个起点:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Fireworks extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private int[] x;
private int[] y;
private int[] colors;
private int n;
private int vx;
private int vy;
private Random random;
public Fireworks(int x, int y) {
this.x = new int[100];
this.y = new int[100];
this.colors = new int[100];
this.n = 100;
this.vx = 10 - (int) (Math.random() * 20);
this.vy = 10 - (int) (Math.random() * 20);
this.random = new Random();
this.setBackground(new Color(0, 0, 0));
for (int i = 0; i < n; i++) {
this.x[i] = x;
this.y[i] = y;
this.colors[i] = this.random.nextInt(255);
}
new Thread(this).start();
}
public void paint(Graphics g) {
super.paint(g);
for (int i = 0; i < n; i++) {
g.setColor(new Color(colors[i], colors[i], colors[i]));
g.fillOval(x[i], y[i], 10, 10);
}
}
public void run() {
while (true) {
for (int i = 0; i < n; i++) {
x[i] += vx;
y[i] += vy;
colors[i] -= 2;
if (colors[i] < 0) {
colors[i] = 0;
}
}
this.repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (colors[0] == 0) {
break;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Fireworks");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(new Fireworks(250, 250));
frame.setVisible(true);
}
}
```
这个代码创建了一个名为“Fireworks”的JFrame窗口,其中包含一个名为“Fireworks”的JPanel面板。当面板被创建时,它显示一个由100个随机颜色的小圆点组成的烟花。这些小圆点随机移动,随着时间的推移,它们的颜色变暗,直到最后消失。
你可以通过修改代码中的参数来改变烟花的颜色、大小、速度和位置,以实现你想要的效果。
阅读全文