Java绝美动态爱心代码
时间: 2024-05-24 16:08:39 浏览: 192
Java绝美动态爱心代码可以通过使用Java Swing编写实现。以下是一个简单的实现示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class Heart extends JPanel implements Runnable {
private double angle = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int width = getWidth();
int height = getHeight();
double centerX = width / 2;
double centerY = height / 2 - 55;
double x, y, r;
GeneralPath heart = new GeneralPath();
r = 50 * Math.sin(angle);
x = centerX + r * Math.cos(angle);
y = centerY - r * Math.sin(angle);
heart.moveTo(x, y);
for (angle = 0; angle <= 2 * Math.PI; angle += 0.01) {
r = 50 * Math.sin(angle);
x = centerX + r * Math.cos(angle);
y = centerY - r * Math.sin(angle);
heart.lineTo(x, y);
}
heart.closePath();
GradientPaint paint = new GradientPaint(0, 0, Color.RED, width, height, Color.PINK);
g2d.setPaint(paint);
g2d.fill(heart);
angle += 0.01;
}
public void run() {
try {
while (true) {
repaint();
Thread.sleep(10);
}
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Dynamic Heart");
frame.add(new Heart());
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Thread thread = new Thread(new Heart());
thread.start();
}
}
```
运行该程序,会显示一个动态的爱心图案,通过改变角度和颜色梯度,可以得到更加漂亮的效果。
阅读全文