用Java画一个爱心
时间: 2023-03-01 21:35:49 浏览: 116
下面是一个使用 Java 实现绘制爱心的示例代码:
```
import java.awt.*;
import javax.swing.*;
public class Heart extends JComponent {
private int width = 300;
private int height = 300;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.RED);
int x = width / 2;
int y = height / 4;
int a = width / 4;
int b = height / 2;
g2.fillArc(x - a, y - b, 2 * a, 2 * b, 0, 180);
g2.fillArc(x - b, y - a, 2 * b, 2 * a, 90, 180);
Polygon p = new Polygon();
p.addPoint(x, y);
p.addPoint(x + a, y + b);
p.addPoint(x - a, y + b);
g2.fillPolygon(p);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Heart());
frame.setVisible(true);
}
}
```
这段代码利用了 Java AWT 和 Swing 包中的图形绘制方法,通过椭圆、扇形和多边形的组合实现了爱心的绘制。
阅读全文