请用Java编写一段可以生成粒子烟花特效的程序
时间: 2023-08-09 19:09:55 浏览: 64
以下是一个简单的Java程序,它可以生成粒子烟花特效:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Fireworks extends JPanel implements ActionListener {
private Timer timer;
private Particle[] particles;
public Fireworks() {
setPreferredSize(new Dimension(500, 500));
setBackground(Color.black);
timer = new Timer(10, this);
timer.start();
particles = new Particle[100];
for (int i = 0; i < particles.length; i++) {
particles[i] = new Particle(getWidth() / 2, getHeight() / 2);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Particle p : particles) {
p.draw(g);
}
}
public void actionPerformed(ActionEvent e) {
for (Particle p : particles) {
p.update();
}
repaint();
}
private class Particle {
private double x, y, vx, vy, ax, ay;
private Color color;
private int size;
public Particle(double x, double y) {
this.x = x;
this.y = y;
vx = Math.random() * 10 - 5;
vy = Math.random() * 10 - 10;
ax = 0;
ay = 0.1;
color = new Color((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256));
size = (int) (Math.random() * 10) + 5;
}
public void update() {
x += vx;
y += vy;
vx += ax;
vy += ay;
size--;
if (size <= 0) {
x = getWidth() / 2;
y = getHeight() / 2;
vx = Math.random() * 10 - 5;
vy = Math.random() * 10 - 10;
ax = 0;
ay = 0.1;
color = new Color((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256));
size = (int) (Math.random() * 10) + 5;
}
}
public void draw(Graphics g) {
g.setColor(color);
g.fillOval((int) x, (int) y, size, size);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Fireworks");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Fireworks());
frame.pack();
frame.setVisible(true);
}
}
```
该程序使用Java的Swing库来绘制粒子烟花特效。它创建了一个继承自JPanel的类,用于绘制烟花。该类包含一个Particle类,该类表示单个粒子。在主函数中,创建一个JFrame并将Fireworks实例添加到其中。运行程序时,将会看到一个不断发射烟花的动画。