用IEDA写一个动态爱心
时间: 2023-10-27 16:05:54 浏览: 108
好的,以下是用Java Swing编写的动态爱心代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
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 ArrayList<Point> hearts = new ArrayList<Point>();
private final int HEART_SIZE = 50; // 爱心大小
private final int HEART_X = 150; // 爱心初始位置
private final int HEART_Y = 150;
private final int HEART_SPEED = 5; // 爱心移动速度
private int dx = HEART_SPEED; // x轴移动距离
private int dy = HEART_SPEED; // y轴移动距离
public DynamicHeart() {
JFrame frame = new JFrame("动态爱心");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(this);
frame.setVisible(true);
hearts.add(new Point(HEART_X, HEART_Y));
new Thread(this).start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
for (Point p : hearts) {
g.fillOval(p.x, p.y, HEART_SIZE, HEART_SIZE);
}
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (Point p : hearts) {
p.x += dx;
p.y += dy;
if (p.x <= 0 || p.x >= getWidth() - HEART_SIZE) {
dx = -dx;
}
if (p.y <= 0 || p.y >= getHeight() - HEART_SIZE) {
dy = -dy;
}
}
repaint();
}
}
public static void main(String[] args) {
new DynamicHeart();
}
}
```
运行以上代码,即可看到一个动态爱心的窗口。当然,你可以根据自己的需求对代码进行修改。
阅读全文