Java怎么做跳动的爱心代码
时间: 2023-11-05 21:03:42 浏览: 47
以下是Java实现跳动的爱心代码的示例:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class JumpingHeart extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private Timer timer;
private int x, y, dx, dy;
private Random rand;
public JumpingHeart() {
setBackground(Color.BLACK);
timer = new Timer(50, this);
timer.start();
rand = new Random();
x = rand.nextInt(600) + 50;
y = rand.nextInt(400) + 50;
dx = rand.nextInt(10) - 5;
dy = rand.nextInt(10) - 5;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Point[] heart = new Point[3];
heart[0] = new Point(x, y + 20);
heart[1] = new Point(x + 20, y);
heart[2] = new Point(x, y - 20);
g.setColor(Color.RED);
g.fillPolygon(heart[0].x, heart[0].y, 3);
g.fillArc(x - 10, y - 20, 20, 40, 0, -180);
}
public void actionPerformed(ActionEvent e) {
x += dx;
y += dy;
if (x < 0 || x > getWidth()) {
dx = -dx;
}
if (y < 0 || y > getHeight()) {
dy = -dy;
}
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Jumping Heart");
frame.setSize(700, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JumpingHeart heart = new JumpingHeart();
frame.add(heart);
frame.setVisible(true);
}
}
```
这个程序使用了Java的Swing库来实现图形界面和动画效果。在构造函数中,设置了背景颜色和定时器,并初始化了心形的位置和速度。在paintComponent方法中,绘制了一个心形和一个弧形。在actionPerformed方法中,更新了心形的位置和速度,并检查是否需要改变方向。最后,在main方法中创建了一个窗口,并将心形添加到窗口中显示。