java写一个带特效的爱心
时间: 2023-05-16 17:07:25 浏览: 86
很高兴回答您的问题!以下是一个使用 Java 编写的带特效的爱心:
```java
import java.awt.*;
import javax.swing.*;
public class HeartAnimation extends JPanel implements Runnable {
private int x, y;
private int size;
private int angle;
private int delay;
public HeartAnimation(int x, int y, int size, int angle, int delay) {
this.x = x;
this.y = y;
this.size = size;
this.angle = angle;
this.delay = delay;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.translate(x, y);
g2d.rotate(Math.toRadians(angle));
g2d.scale(size, size);
g2d.setColor(Color.RED);
g2d.fillOval(-10, -10, 20, 20);
g2d.fillOval(0, -10, 20, 20);
g2d.fillPolygon(new int[] {-10, 0, 10}, new int[] {0, 20, 0}, 3);
g2d.rotate(Math.toRadians(-angle));
g2d.translate(-x, -y);
}
@Override
public void run() {
try {
while (true) {
angle += 5;
size += 0.01;
x += 2 * Math.sin(Math.toRadians(angle));
y += 2 * Math.cos(Math.toRadians(angle));
Thread.sleep(delay);
repaint();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
HeartAnimation heart = new HeartAnimation(200, 200, 1, 0, 10);
frame.add(heart);
frame.setVisible(true);
new Thread(heart).start();
}
}
```
这个程序使用 Java Swing 绘制一个带特效的爱心,可以在窗口中移动和旋转。您可以在 main 方法中修改 x、y、size、angle 和 delay 参数来调整爱心的位置、大小、旋转速度和动画延迟。希望这个程序能够帮助到您!
阅读全文