Java生成粉色转动爱心
时间: 2023-05-19 12:04:38 浏览: 93
Java实现爱心小功能附带源码
以下是Java生成粉色转动爱心的代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PinkHeart extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private int x = 300, y = 200;
private double t = 0;
private int r = 100;
public PinkHeart() {
JFrame frame = new JFrame("粉色转动爱心");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setVisible(true);
}
public void paint(Graphics g) {
g.setColor(Color.PINK);
int x1 = (int) (x + r * (16 * Math.pow(Math.sin(t), 3)));
int y1 = (int) (y - r * (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)));
int x2 = (int) (x + r * (16 * Math.pow(Math.sin(t + Math.PI), 3)));
int y2 = (int) (y - r * (13 * Math.cos(t + Math.PI) - 5 * Math.cos(2 * (t + Math.PI)) - 2 * Math.cos(3 * (t + Math.PI)) - Math.cos(4 * (t + Math.PI))));
g.drawLine(x1, y1, x2, y2);
}
public void run() {
while (true) {
t += 0.05;
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
PinkHeart heart = new PinkHeart();
Thread thread = new Thread(heart);
thread.start();
}
}
```
运行该程序,即可看到粉色转动爱心的效果。
注意:该程序中使用了Java的图形库,需要在Java环境下运行。
阅读全文