用java爱心跳动代码
时间: 2023-11-15 13:03:14 浏览: 240
以下是一个简单的Java爱心跳动代码,它使用了Java的Swing库来实现图形化界面和动画效果。代码中使用了数学函数来计算爱心的坐标,然后通过绘制图形来实现动画效果。
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class HeartBeat extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private Timer timer;
private int angle = 0;
private int radius = 100;
private int centerX = 250;
private int centerY = 250;
public HeartBeat() {
timer = new Timer(10, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
Point p1 = getHeartPoint(angle);
Point p2 = getHeartPoint(angle + 180);
g.drawLine(centerX + p1.x, centerY - p1.y, centerX + p2.x, centerY - p2.y);
}
public Point getHeartPoint(int angle) {
double t = (double) angle / 180 * Math.PI;
double x = radius * (16 * Math.pow(Math.sin(t), 3));
double y = -radius * (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t));
return new Point((int) x, (int) y);
}
public void actionPerformed(ActionEvent e) {
angle++;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Java爱心跳动代码");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setContentPane(new HeartBeat());
frame.setVisible(true);
}
}
```
阅读全文