java 语言 实现一个跳动的心
时间: 2024-05-01 19:16:51 浏览: 78
Java实现心跳机制的方法
5星 · 资源好评率100%
以下是Java实现一个跳动的心的代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class Heart extends JPanel {
private static final long serialVersionUID = 1L;
private static final int SIZE = 200;
private static final int RATE = 30;
private int x = SIZE / 2;
private int y = SIZE / 2;
private int r = SIZE / 3;
private int t = 0;
public Heart() {
Timer timer = new Timer(RATE, e -> {
t++;
repaint();
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 计算心形曲线
Path2D path = new Path2D.Double();
double step = Math.PI / 180;
double x, y, r;
for (double theta = 0; theta <= 2 * Math.PI; theta += step) {
r = this.r * (1 + Math.sin(theta + t * step));
x = this.x + r * Math.cos(theta);
y = this.y + r * Math.sin(theta);
if (theta == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
}
path.closePath();
// 绘制心形曲线
g2.setColor(new Color(255, 0, 0));
g2.fill(path);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(SIZE, SIZE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setContentPane(new Heart());
frame.setVisible(true);
}
}
```
该程序主要利用了Java的Swing图形库绘制一个跳动的心形曲线。其中,`Heart`类继承自`JPanel`,重写了`paintComponent`方法,在该方法中计算心形曲线的路径,并绘制出来。程序中通过定时器每隔一段时间重新绘制界面,实现心形曲线的跳动效果。最后,利用`main`方法创建一个窗口并将`Heart`添加到其中,运行程序即可看到跳动的心形曲线。
阅读全文