java烟花代码动态网页
时间: 2024-05-02 18:13:38 浏览: 235
以下是一个使用Java编写的烟花特效的动态网页代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
public class FireworksWebPage extends JFrame {
private List<Firework> fireworks;
public FireworksWebPage() {
setTitle("烟花特效");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fireworks = new ArrayList<>();
FireworksPanel panel = new FireworksPanel();
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
fireworks.add(new Firework(e.getX(), e.getY()));
}
});
add(panel);
setVisible(true);
animate();
}
private void animate() {
while (true) {
for (Firework firework : fireworks) {
firework.update();
}
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private class FireworksPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Firework firework : fireworks) {
firework.draw(g);
}
}
}
private class Firework {
private int x;
private int y;
private int size;
private Color color;
private int speed;
public Firework(int x, int y) {
this.x = x;
this.y = y;
this.size = 5;
this.color = new Color((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256));
this.speed = (int) (Math.random() * 5) + 1;
}
public void update() {
y -= speed;
size += 1;
if (size >= 50) {
fireworks.remove(this);
}
}
public void draw(Graphics g) {
g.setColor(color);
g.fillOval(x - size / 2, y - size / 2, size, size);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(FireworksWebPage::new);
}
}
```
阅读全文