java的动态爱心代码
时间: 2024-05-17 20:11:11 浏览: 22
Java的动态爱心代码可以通过Java的Swing框架来实现。以下是一个简单的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 int x, y;
private double t = 0;
private int width = 500;
private int height = 500;
public Heart() {
JFrame frame = new JFrame("动态爱心");
frame.setSize(width, height);
frame.add(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Thread thread = new Thread(this);
thread.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
for (int i = 0; i < 360; i++) {
double r = Math.PI / 45 * i;
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.fillOval((int) (width / 2 + x), (int) (height / 2 + y), 2, 2);
}
}
@Override
public void run() {
while (true) {
t += 0.05;
x = (int) (16 * Math.pow(Math.sin(t), 3));
y = (int) (-13 * Math.cos(t) + 5 * Math.cos(2 * t) + 2 * Math.cos(3 * t) + Math.cos(4 * t));
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Heart();
}
}
```
该代码使用了Swing框架,实现了一个在窗口中不断运动的动态爱心,可以通过运行该代码来查看效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)