跨年烟花源代码java
时间: 2025-01-06 11:21:59 浏览: 10
### Java 实现跨年烟花效果
为了实现跨年烟花的效果,在Java中可以利用图形界面库Swing来绘制动画。下面是一个简单的例子,通过随机生成不同颜色和位置的圆形模拟烟花爆炸的效果[^1]。
```java
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Fireworks extends JPanel implements Runnable {
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 600;
private Thread animator;
private boolean running = false;
public void start() {
if (animator == null || !running) {
animator = new Thread(this);
running = true;
animator.start();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawFirework((Graphics2D)g.create());
}
private void drawFirework(Graphics2D g2d){
Random random = new Random();
// 设置背景为黑色
setBackground(Color.BLACK);
for(int i=0; i<50 ;i++){
Color color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
int x = random.nextInt(FRAME_WIDTH);
int y = random.nextInt(FRAME_HEIGHT);
g2d.setColor(color);
g2d.fillOval(x, y, 10, 10);
}
}
@Override
public void run(){
while(running){
repaint();
try{
Thread.sleep(100);
}catch(Exception e){}
}
}
public static void main(String[] args)throws Exception{
JFrame frame = new JFrame("New Year's Eve Fireworks");
Fireworks fireworksPanel = new Fireworks();
frame.add(fireworksPanel,BorderLayout.CENTER);
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
fireworksPanel.start();
}
}
```
这段代码创建了一个名为`Fireworks`的类继承自JPanel并实现了Runnable接口以便启动线程更新画面。程序会持续不断地重绘组件,每次都会随机产生新的彩色圆圈代表绽放中的烟火,从而形成动态变化的画面效果[^1]。
阅读全文