用java实现一个跳动的心
时间: 2024-01-07 12:04:12 浏览: 138
抱歉,作为AI语言模型,我无法演示出跳动的心的图形效果。但是,我可以提供一份Java代码,供您参考:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Heart extends JPanel {
private static final long serialVersionUID = 1L;
private int x = 220;
private int y = 150;
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillOval(x, y, 30, 30);
g.fillOval(x + 40, y, 30, 30);
int[] xs = { x - 5, x + 75, x + 35, x - 35 };
int[] ys = { y + 30, y + 30, y + 90, y + 90 };
g.fillPolygon(xs, ys, 4);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("跳动的心");
Heart heart = new Heart();
frame.add(heart);
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
heart.moveHeart();
heart.repaint();
Thread.sleep(20);
}
}
private void moveHeart() {
x = x + (int) (Math.random() * 10) - 5;
y = y + (int) (Math.random() * 10) - 5;
}
}
```
这段代码实现了一个跳动的红色心形图案。每20毫秒,心形图案会随机移动。您可以将此代码复制到Java IDE中,运行并观察效果。
阅读全文