用Java写一个会跳动的爱心代码
时间: 2023-11-22 13:42:24 浏览: 32
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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 int x = 200;
private int y = 200;
private double t = 0;
private Timer timer;
public JumpingHeart() {
timer = new Timer(10, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
drawHeart(g, x, y);
}
public void drawHeart(Graphics g, int x, int y) {
g.setColor(Color.RED);
int[] xPoints = new int[7];
int[] yPoints = new int[7];
xPoints[0] = x;
yPoints[0] = y + 30;
xPoints[1] = x - 30;
yPoints[1] = y;
xPoints[2] = x;
yPoints[2] = y - 30;
xPoints[3] = x + 30;
yPoints[3] = y;
xPoints[4] = x + 25;
yPoints[4] = y + 20;
xPoints[5] = x;
yPoints[5] = y + 50;
xPoints[6] = x - 25;
yPoints[6] = y + 20;
g.fillPolygon(xPoints, yPoints, 7);
}
public void actionPerformed(ActionEvent e) {
t += 0.05;
x = (int) (200 + 50 * Math.sin(t));
y = (int) (200 + 50 * (Math.sin(t) + Math.cos(t)));
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Jumping Heart");
frame.setSize(400, 400);
JumpingHeart heart = new JumpingHeart();
frame.add(heart);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```