java 画一个爱心
时间: 2023-09-03 09:25:07 浏览: 126
### 回答1:
以下是一段使用 Java 画爱心的代码示例:
import java.awt.*;
import javax.swing.*;
public class Heart extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.RED);
int x = getWidth() / 2;
int y = getHeight() / 2;
int a = x - 50;
int b = y - 50;
g2.fillArc(a, b, 100, 100, 45, 270);
g2.fillArc(a + 35, b, 100, 100, 135, 270);
g2.fillRect(x, y - 50, 35, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Heart());
frame.setVisible(true);
}
}
这段代码会在 Java 的图形界面绘制一个红色的爱心图形。
### 回答2:
要使用Java来画一个爱心,可以使用Java Graphics类的方法来实现。下面是一个简单的实现方式:
```java
import javax.swing.*;
import java.awt.*;
public class HeartDrawing extends JFrame {
private final int WIDTH = 300;
private final int HEIGHT = 300;
public HeartDrawing() {
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("爱心绘制");
setLocationRelativeTo(null);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(3));
int centerX = WIDTH / 2;
int centerY = HEIGHT / 2;
int radius = 100;
g2d.drawArc(centerX - radius / 2, centerY - radius / 2, radius, radius, 0, 180);
g2d.drawArc(centerX, centerY - radius / 2, radius, radius, 0, 180);
int[] xPoints = {centerX - radius / 2, centerX + radius, centerX};
int[] yPoints = {centerY, centerY, centerY + radius - 20};
g2d.fillPolygon(xPoints, yPoints, 3);
}
public static void main(String[] args) {
HeartDrawing heartDrawing = new HeartDrawing();
heartDrawing.setVisible(true);
}
}
```
这段代码创建了一个窗口,并在窗口中使用Graphics类的方法绘制了一个爱心的图形。首先,确定了爱心的中心点坐标和半径,然后使用`drawArc`方法绘制了两个圆弧,最后使用`fillPolygon`方法绘制了爱心的尖端。执行该代码后,将会在窗口中看到一个画好的爱心图形。
阅读全文