用Java写个爱心程序
时间: 2024-02-28 12:53:10 浏览: 63
以下是用Java编写的绘制爱心的程序:
```java
import java.awt.*;
import javax.swing.*;
public class Heart extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3.0f));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
int x = getWidth() / 2 - 50;
int y = getHeight() / 2 - 50;
int width = 100;
int height = 100;
int cp_x1 = x + width / 4;
int cp_y1 = y - height / 2;
int cp_x2 = x - width / 2;
int cp_y2 = y + height / 4;
g2d.fillArc(cp_x1, cp_y1, width / 2, height / 2, 0, 180);
g2d.fillArc(cp_x2, cp_y2, width / 2, height / 2, 0, 180);
g2d.fillRect(x + width / 4, y, width / 2, height / 2);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
Heart panel = new Heart();
frame.setContentPane(panel);
frame.setVisible(true);
}
}
```
运行该程序可以绘制一个红色的爱心形状在窗口中间。
阅读全文