java写一个动态的爱心
时间: 2023-07-15 19:11:29 浏览: 82
以下是使用Java Swing编写的动态爱心:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DynamicHeart extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private int x, y;
private ArrayList<Point> points = new ArrayList<>();
private Thread thread;
public DynamicHeart() {
setBackground(Color.BLACK);
thread = new Thread(this);
thread.start();
}
@Override
public void run() {
while (true) {
int dx = (int) ((Math.random() - 0.5) * 3);
int dy = (int) ((Math.random() - 0.5) * 3);
x += dx;
y += dy;
if (x < 0 || x > getWidth()) {
x -= dx;
}
if (y < 0 || y > getHeight()) {
y -= dy;
}
Point point = new Point(x, y);
points.add(point);
if (points.size() > 50) {
points.remove(0);
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
for (int i = 0; i < points.size(); i++) {
Point p = points.get(i);
g.fillOval(p.getX(), p.getY(), 10, 10);
}
}
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DynamicHeart());
frame.setVisible(true);
}
}
```
运行程序后,会在窗口中生成一个动态的红色爱心。爱心的位置是随机变化的,同时会留下一条轨迹。
阅读全文