Java画会跳动的爱心
时间: 2023-07-28 10:06:36 浏览: 166
以下是Java代码,可以画出跳动的爱心:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Heart extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 600; // 窗口宽度
private static final int HEIGHT = 600; // 窗口高度
private int x; // x坐标
private int y; // y坐标
private double t; // 参数t
public Heart() {
x = 300;
y = 100;
t = 0;
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
for (int i = 0; i < 360; i++) {
double r = Math.PI * i / 180;
double x = 16 * Math.pow(Math.sin(r), 3);
double y = 13 * Math.cos(r) - 5 * Math.cos(2 * r) - 2 * Math.cos(3 * r) - Math.cos(4 * r);
g.drawLine((int) x + this.x, (int) y + this.y, (int) x + this.x, (int) y + this.y);
}
}
public void run() {
while (true) {
t += 0.05;
x = (int) (150 * (16 * Math.pow(Math.sin(t), 3)));
y = (int) (150 * (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)));
repaint();
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Heart heart = new Heart();
frame.add(heart);
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Thread(heart).start();
}
}
```
该程序创建了一个JFrame窗口,在窗口中画出了一个跳动的爱心。程序使用了数学函数来计算爱心的坐标,并通过不断更新坐标来实现跳动效果。
阅读全文