java里面生成一个会跳动的爱心
时间: 2023-07-15 20:11:21 浏览: 136
你可以使用Java Swing库来实现一个跳动的爱心。下面是一个简单的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class HeartAnimation extends JPanel implements Runnable {
private double angle = 0;
private double x = 0;
private double y = 0;
public HeartAnimation() {
setPreferredSize(new Dimension(400, 400));
Thread thread = new Thread(this);
thread.start();
}
public void run() {
while (true) {
angle += 0.1;
x = 160 + 100 * Math.pow(Math.sin(angle), 3);
y = 130 - 100 * Math.cos(angle) + 50 * Math.cos(2 * angle) + 30 * Math.cos(3 * angle) + 20 * Math.cos(4 * angle);
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.RED);
Shape heart = new Ellipse2D.Double(x - 25, y - 25, 50, 50);
g2d.fill(heart);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new HeartAnimation());
frame.pack();
frame.setVisible(true);
}
}
```
这个示例代码使用了心形方程来计算爱心的坐标,并且使用了Java Swing的图形库来绘制出来。可以通过调整心形方程中的参数来实现不同的效果。
阅读全文