java实现绘制桃心(附完整源码)
时间: 2023-11-12 19:05:03 浏览: 144
易语言实现五颜六色桃心源码
以下是 Java 实现绘制桃心的完整源码:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PeachHeart extends JPanel {
// 定义桃心大小和位置
private static final int WIDTH = 200;
private static final int HEIGHT = 200;
private static final int X_POSITION = 100;
private static final int Y_POSITION = 100;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
// 绘制左半边桃心
g.fillArc(X_POSITION - WIDTH / 4, Y_POSITION - HEIGHT / 4, WIDTH / 2, HEIGHT / 2, 0, 180);
g.fillArc(X_POSITION - WIDTH / 4, Y_POSITION, WIDTH / 2, HEIGHT / 2, 0, 180);
// 绘制右半边桃心
g.fillArc(X_POSITION, Y_POSITION - HEIGHT / 4, WIDTH / 2, HEIGHT / 2, 0, 180);
g.fillArc(X_POSITION, Y_POSITION, WIDTH / 2, HEIGHT / 2, 0, 180);
// 绘制两个圆弧之间的矩形
g.fillRect(X_POSITION - WIDTH / 4, Y_POSITION - HEIGHT / 4, WIDTH / 2, HEIGHT / 2);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PeachHeart panel = new PeachHeart();
frame.add(panel);
frame.setVisible(true);
}
}
```
运行该程序将会显示一个红色的桃心形状。其中,`paintComponent` 方法用于绘制桃心的形状,`main` 方法创建一个 `JFrame` 窗口并将 `PeachHeart` 面板添加到窗口中。
阅读全文