java写一个爱心形状
时间: 2023-12-21 16:04:11 浏览: 34
以下是使用Java绘制爱心形状的示例代码:
```java
import java.awt.*;
import javax.swing.*;
public class HeartShape extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(2));
g2d.setColor(Color.RED);
int x = getWidth() / 2;
int y = getHeight() / 2;
int size = Math.min(x, y) * 2 / 3;
// 绘制爱心的两个半圆
int cx = x - size / 4;
int cy = y - size / 4;
int cr = size / 2;
g2d.drawArc(cx, cy, cr, cr, 0, 180);
cx += size / 2;
g2d.drawArc(cx, cy, cr, cr, 0, 180);
// 绘制爱心的两条线段
int l = (int) (cr / Math.sqrt(2));
int lx = x - l;
int ly = y + l;
g2d.drawLine(lx, ly, cx, cy + cr);
lx = x + l;
g2d.drawLine(lx, ly, cx, cy + cr);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart Shape");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
HeartShape heart = new HeartShape();
frame.add(heart);
frame.setVisible(true);
}
}
```
在`paintComponent`方法中,我们使用`Graphics2D`对象绘制爱心图形。该方法首先调用父类的`paintComponent`方法以确保面板正确绘制。然后,我们设置抗锯齿和线条粗细等绘图属性,以及爱心的颜色。接下来,我们计算出爱心的大小和位置,并使用`drawArc`方法绘制两个半圆。最后,我们使用`drawLine`方法绘制两条线段,以连接半圆的上方。在`main`方法中,我们创建一个`JFrame`并将`HeartShape`对象添加到其中,然后显示窗口。
运行该程序后,您将看到一个红色的爱心形状在窗口中央。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)