给我java爱心代码高级
时间: 2024-10-13 13:13:47 浏览: 44
在Java中,如果你想创建一个简单的图形表示爱心,可以使用Graphics类绘制基本形状。这里有一个简单的例子,用两个相连的圆形来模拟爱心:
```java
import javax.swing.*;
import java.awt.*;
public class HeartShape extends JFrame {
public HeartShape() {
setSize(200, 200); // 设置窗口大小
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // 居中显示
setLayout(null); // 使用绝对布局
// 创建红色的心形背景
Color color = new Color(255, 0, 127); // 红色
Graphics graphics = getGraphics();
graphics.setColor(color);
graphics.fillRect(0, 0, getWidth(), getHeight());
// 创建白色爱心
graphics.setColor(Color.WHITE);
int radius = 60; // 圆心到边界的半径
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
// 上部小圆
graphics.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
// 下部大圆
graphics.drawOval(centerX - radius, centerY + radius, radius * 2, radius * 2);
// 连接两圆
graphics.drawLine(centerX, centerY - radius, centerX, centerY + radius);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new HeartShape();
}
});
}
}
```
运行这个程序会在JFrame上看到一个红色背景和白色的爱心图案。
阅读全文
相关推荐


















