用java写一个动态爱心
时间: 2024-05-11 08:14:11 浏览: 8
下面是一个使用 Java 实现动态爱心的示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
public class LoveHeart extends JComponent {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int x = 0;
int y = 0;
float width = WIDTH;
float height = HEIGHT;
Ellipse2D.Float circle = new Ellipse2D.Float(x, y + height / 4, width, height / 2);
g2.setPaint(Color.pink);
g2.fill(circle);
GeneralPath gp = new GeneralPath();
gp.moveTo(x + width / 2, y + height / 4);
gp.curveTo(x + width / 4, y, x, y + height / 2, x + width / 2, y + height * 3 / 4);
gp.curveTo(x + width, y + height / 2, x + width * 3 / 4, y, x + width / 2, y + height / 4);
gp.closePath();
g2.setPaint(Color.red);
g2.fill(gp);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LoveHeart());
frame.setVisible(true);
}
}
```
该代码利用了 Java2D 库中的图形绘制功能,通过绘制圆形和曲线,实现了一个动态的爱心图形。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)