在idea中java动态画爱心代码
时间: 2024-05-04 09:16:40 浏览: 14
好的,您需要使用Java Swing来实现动态画爱心的代码。以下是参考代码:
``` java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DynamicHeartDemo extends JPanel {
private static final long serialVersionUID = 1L;
private int refresh = 20;
private int size = 10;
private List<Point> points = new ArrayList<Point>();
public DynamicHeartDemo() {
setBackground(Color.white);
}
@Override
public void paint(Graphics g) {
super.paint(g);
for (Point p : points) {
int x = p.x;
int y = p.y;
g.fillOval(x, y, size, size);
}
}
private void drawHeart() {
for (double t = 0; t <= Math.PI; t += 0.01) {
int x = (int) (16 * Math.pow(Math.sin(t), 3));
int y = (int) (13 * Math.cos(t) - 5 * Math.cos(2 * t)
- 2 * Math.cos(3 * t) - Math.cos(4 * t));
x = x * size + getWidth() / 2;
y = -y * size + getHeight() / 2;
points.add(new Point(x, y));
}
}
public void start() {
drawHeart();
while (true) {
try {
Thread.sleep(refresh);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<Point> removePoints = new ArrayList<Point>();
for (Point p : points) {
if (p.y <= 0) {
removePoints.add(p);
continue;
}
p.x -= 1;
p.y -= 1;
}
points.removeAll(removePoints);
repaint();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DynamicHeartDemo panel = new DynamicHeartDemo();
frame.add(panel);
frame.setVisible(true);
panel.start();
}
}
```
这段代码可以在Java开发工具IDEA中使用。您只需要将以上代码复制到您的IDEA项目中,然后运行即可。希望能够帮到您!