用eclipse程序写一份关于Java语言的动态烟花效果的代码,运行该程序,将会看到一个动态的烟花效果。每隔一秒钟会发射一颗烟花,烟花会在空中爆炸,产生多个颜色不同的粒子,粒子会逐渐消失。
时间: 2024-02-16 19:59:46 浏览: 44
以下是一份Java语言的动态烟花效果的代码,您可以在Eclipse中创建一个Java项目,将以下代码复制到Main.java中,并运行该程序,即可看到动态的烟花效果:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private Timer timer;
private List<Particle> particles;
public Main() {
particles = new ArrayList<Particle>();
timer = new Timer(1000, this);
timer.start();
}
public void actionPerformed(ActionEvent e) {
particles.add(new Particle(getWidth() / 2, getHeight() - 10));
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Particle particle : particles) {
particle.draw(g2d);
}
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Dynamic Fireworks");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
Main main = new Main();
frame.add(main);
frame.setVisible(true);
}
private class Particle {
private float x;
private float y;
private float dx;
private float dy;
private float gravity;
private int alpha;
private Color color;
public Particle(float x, float y) {
this.x = x;
this.y = y;
this.dx = new Random().nextFloat() * 10 - 5;
this.dy = new Random().nextFloat() * -12;
this.gravity = 0.5f;
this.alpha = 255;
this.color = new Color(new Random().nextInt(256), new Random().nextInt(256), new Random().nextInt(256));
}
public void draw(Graphics2D g2d) {
if (alpha > 0) {
g2d.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha));
g2d.fillOval((int) x, (int) y, 10, 10);
x += dx;
y += dy;
dy += gravity;
alpha -= 5;
} else {
particles.remove(this);
}
}
}
}
```
代码中使用了Java Swing来实现GUI界面,使用了Java Timer来实现每隔一秒钟发射烟花的功能,使用了Java Graphics2D来绘制粒子效果,并使用了Java Random来生成不同颜色和位置的粒子。
在Particle类中,使用了alpha变量来控制粒子的透明度,当透明度为0时,将粒子从particles列表中移除,实现了粒子消失的逻辑。
希望这份代码能够帮到您!
阅读全文