用java编写一个跳动的心型代码
时间: 2024-06-09 08:12:05 浏览: 105
Java实现心跳机制的方法
5星 · 资源好评率100%
以下用Java Swing编写的跳动的心型代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class HeartBeat extends JPanel implements ActionListener {
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final int DELAY = 10;
private static final int POINTS = 100;
private static final int RADIUS = 150;
private Timer timer;
private int[] xPoints;
private int[] yPoints;
private int angle = 0;
private int direction = 1;
public HeartBeat() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
timer = new Timer(DELAY, this);
timer.start();
}
private void calculatePoints() {
xPoints = new int[POINTS];
yPoints = new int[POINTS];
for (int i = 0; i < POINTS; i++) {
double theta = 2 * Math.PI * i / POINTS;
double x = RADIUS * (16 * Math.pow(Math.sin(theta), 3));
double y = -RADIUS * (13 * Math.cos(theta) - 5 * Math.cos(2 * theta) - 2 * Math.cos(3 * theta) - Math.cos(4 * theta));
xPoints[i] = (int) x + WIDTH / 2;
yPoints[i] = (int) y + HEIGHT / 2;
}
}
@Override
public void actionPerformed(ActionEvent e) {
angle += direction;
if (angle >= 180 || angle <= 0) {
direction *= -1;
}
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
calculatePoints();
g2d.setColor(Color.RED);
g2d.rotate(Math.toRadians(angle), WIDTH / 2, HEIGHT / 2);
g2d.fillPolygon(xPoints, yPoints, POINTS);
g2d.rotate(Math.toRadians(-angle), WIDTH / 2, HEIGHT / 2);
g2d.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heartbeat");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new HeartBeat());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
这个代码使用了心形曲线的极坐标方程,并通过旋转来实现心形的跳动效果。
阅读全文