用java写一个跳动的爱心
时间: 2024-03-22 20:38:49 浏览: 104
以下是用 Java Swing 实现的跳动爱心代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class HeartAnimation extends JPanel {
private static final long serialVersionUID = 1L;
private static final int HEART_WIDTH = 50;
private static final int HEART_HEIGHT = 50;
private static final int DELTA = 5;
private int x = 0;
private int y = 0;
private int dx = DELTA;
private int dy = DELTA;
public HeartAnimation() {
Timer timer = new Timer(30, e -> {
x += dx;
y += dy;
if (x < 0 || x + HEART_WIDTH > getWidth()) {
dx = -dx;
}
if (y < 0 || y + HEART_HEIGHT > getHeight()) {
dy = -dy;
}
repaint();
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int cx = x + HEART_WIDTH / 2;
int cy = y + HEART_HEIGHT / 2;
Ellipse2D.Double ellipse1 = new Ellipse2D.Double(x, y, HEART_WIDTH / 2, HEART_HEIGHT / 2);
Ellipse2D.Double ellipse2 = new Ellipse2D.Double(cx, y, HEART_WIDTH / 2, HEART_HEIGHT / 2);
GeneralPath path = new GeneralPath();
path.moveTo(x, cy);
path.curveTo(x, y - HEART_HEIGHT / 4, cx - HEART_WIDTH / 4, y, cx, y);
path.curveTo(cx + HEART_WIDTH / 4, y, x + HEART_WIDTH, y - HEART_HEIGHT / 4, x + HEART_WIDTH, cy);
path.curveTo(x + HEART_WIDTH, y + HEART_HEIGHT / 4, cx + HEART_WIDTH / 4, y + HEART_HEIGHT, cx, y + HEART_HEIGHT);
path.curveTo(cx - HEART_WIDTH / 4, y + HEART_HEIGHT, x, y + HEART_HEIGHT / 4, x, cy);
g2d.setColor(Color.RED);
g2d.fill(ellipse1);
g2d.fill(ellipse2);
g2d.fill(path);
g2d.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setContentPane(new HeartAnimation());
frame.setVisible(true);
}
}
```
运行后会出现一个窗口,里面有一个跳动的爱心,可以通过改变 DELTA 常量的值来改变爱心的移动速度。
阅读全文