java会跳动的爱心代码
时间: 2024-05-30 11:06:12 浏览: 80
Java中可以用Swing来实现跳动的爱心代码。以下是一个简单的实现示例:
```
import javax.swing.*;
import java.awt.*;
public class Heart extends JFrame {
public Heart() {
this.setSize(600, 600);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyJPanel myJPanel = new MyJPanel();
this.add(myJPanel);
this.setVisible(true);
}
public static void main(String[] args) {
new Heart();
}
}
class MyJPanel extends JPanel implements Runnable {
private int x;
private int y;
private double i;
public MyJPanel() {
x = 270;
y = 240;
i = 0;
new Thread(this).start();
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
for (i = 0; i <= 2 * Math.PI; i += 0.05) {
double x1 = 16 * Math.pow(Math.sin(i), 3);
double y1 = 13 * Math.cos(i) - 5 * Math.cos(2 * i) - 2 * Math.cos(3 * i) - Math.cos(4 * i);
g.fillRect((int) (x + x1), (int) (y - y1), 2, 2);
}
}
public void run() {
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
x -= 3;
y -= 3;
repaint();
}
}
}
```
如果你运行这个程序,你就会看到一个跳动的爱心。同时,以下是一些相关问题:
阅读全文