Java爱心烟花特效代码
时间: 2024-11-05 13:32:32 浏览: 30
在Java中创建爱心烟花特效的代码通常涉及到图形绘制、动画以及随机数生成等部分。下面是一个简单的示例,使用Swing库来画出爱心形状并在每次循环中改变位置:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Arc2D;
import java.util.Random;
public class HeartFireworks extends JFrame {
private int x = 50;
private int y = 50;
private Random random = new Random();
private Color color;
public HeartFireworks() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
// 创建爱心形状
Graphics2D g = createGraphics();
g.setColor(Color.WHITE);
g.setStroke(new BasicStroke(2));
g.draw(new Arc2D.Float(x, y, 70, 70, -180, 90, Arc2D.OPEN));
startAnimation();
}
private void startAnimation() {
Timer timer = new Timer(50, e -> {
x += random.nextInt(10) - 5; // 随机移动X轴
y += random.nextInt(10) - 5; // 随机移动Y轴
if (x > getWidth() || x < 0 || y > getHeight() || y < 0) {
stopAnimation(); // 当超出边界时停止动画
return;
}
repaint(); // 刷新屏幕更新爱心的位置
});
timer.start();
}
private void stopAnimation() {
((TimerTask) SwingUtilities.invokeLater(() -> timer.stop())).cancel();
}
@Override
protected void paint(Graphics g) {
super.paint(g);
g.setColor(color);
g.setStroke(new BasicStroke(2));
g.draw(new Arc2D.Float(x, y, 70, 70, -180, 90, Arc2D.OPEN));
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
HeartFireworks window = new HeartFireworks();
window.setVisible(true);
});
}
}
阅读全文