用java做一个爱心
时间: 2023-02-25 15:45:53 浏览: 80
在 Java 中,可以使用图形绘制工具绘制爱心图案。
以下是一个简单的示例代码:
```
import java.awt.*;
import javax.swing.*;
public class Heart extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int x = getWidth() / 2;
int y = getHeight() / 2;
int a = Math.min(x, y);
int b = a / 2;
int c = (int) (a * Math.sin(Math.toRadians(30)));
g2d.translate(x, y);
g2d.setPaint(Color.red);
g2d.fillPolygon(new int[] { -b, c, b, c }, new int[] { -a, -c, -c, a }, 4);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.add(new Heart());
frame.setVisible(true);
}
}
```
这段代码中,我们继承了 `JComponent` 类,并重写了其中的 `paintComponent` 方法。在该方法中,我们使用图形绘制工具绘制了一个爱心图案。
运行该代码,可以看到一个显示爱心的窗口。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)