Java爱心动画代码
时间: 2023-07-02 10:11:19 浏览: 68
以下是一个简单的Java爱心动画代码。
```java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class HeartAnimation extends JPanel implements Runnable {
private List<Point> heartPoints;
private int size;
private Color color;
private int x;
private int y;
public HeartAnimation(int size, Color color, int x, int y) {
this.size = size;
this.color = color;
this.x = x;
this.y = y;
this.setPreferredSize(new Dimension(size, size));
this.heartPoints = new ArrayList<>();
this.createHeart();
}
private void createHeart() {
for (double t = 0; t <= Math.PI * 2; t += 0.01) {
int x = (int) (16 * Math.pow(Math.sin(t), 3));
int y = (int) (-13 * Math.cos(t) + 5 * Math.cos(2 * t) + 2 * Math.cos(3 * t) + Math.cos(4 * t));
Point point = new Point(x * 10, y * 10);
this.heartPoints.add(point);
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(this.color);
for (Point point : this.heartPoints) {
int x = point.x + this.x;
int y = point.y + this.y;
g.drawLine(x, y, x, y);
}
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
this.x += 1;
this.y += 1;
this.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
HeartAnimation heartAnimation = new HeartAnimation(400, Color.RED, 100, 100);
frame.add(heartAnimation);
frame.pack();
frame.setVisible(true);
Thread thread = new Thread(heartAnimation);
thread.start();
}
}
```
这个程序创建了一个继承自JPanel的类HeartAnimation,它绘制了一个爱心图案。在run()方法中,它通过每10毫秒将x和y坐标增加1来实现动画效果。在main()方法中,我们将HeartAnimation添加到JFrame并启动动画线程。