idea中java实现爱心代码
时间: 2024-10-17 15:02:11 浏览: 32
在IntelliJ IDEA中,如果你想用Java语言绘制一个简单的爱心图案,可以使用Swing库或者JavaFX图形API。这里提供一个简单的Swing代码示例,它创建了一个由矩形组成的爱心:
```java
import javax.swing.*;
import java.awt.*;
public class LoveHeart extends JFrame {
public LoveHeart() {
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 创建心形区域
JPanel lovePanel = new JPanel();
lovePanel.setLayout(null);
lovePanel.setBackground(Color.RED);
// 上半部分弧线
Rectangle upperHalf = new Rectangle(50, 75, 150, 150);
upperHalf.setArc(45, -90, 180, 180);
lovePanel.add(upperHalf);
// 下半部分两个三角形
int triangleLength = 50;
Triangle leftTriangle = new Triangle(lovePanel.getWidth() / 2 - triangleLength, lovePanel.getHeight() / 2 + triangleLength, triangleLength);
Triangle rightTriangle = new Triangle(lovePanel.getWidth() / 2 + triangleLength, lovePanel.getHeight() / 2 + triangleLength, triangleLength);
lovePanel.add(leftTriangle);
lovePanel.add(rightTriangle);
add(lovePanel);
setVisible(true);
}
private static class Triangle extends JPanel {
private int x, y, length;
Triangle(int x, int y, int length) {
this.x = x;
this.y = y;
this.length = length;
setBackground(Color.RED);
setOpaque(true); // 设置背景可见
setPreferredSize(new Dimension(length, length));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillPolygon(new int[]{x, x+length, x-length}, new int[]{y, y, y+length}, 3);
}
}
public static void main(String[] args) {
new LoveHeart();
}
}
```
阅读全文