Java代码画一个爱心
时间: 2023-05-22 09:05:36 浏览: 107
使用Python画出小人发射爱心的代码
5星 · 资源好评率100%
这是Java画一个爱心的代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class HeartDrawing extends JPanel {
// 定义窗口大小
private static final int WIDTH = 600;
private static final int HEIGHT = 600;
private void drawHeart(Graphics g) {
// 设置画笔颜色为红色
g.setColor(Color.RED);
// 计算心形曲线上的点坐标
int x, y;
double t;
for (int i = -135; i <= 135; i++) {
t = i * Math.PI / 45;
x = (int) (16 * Math.sin(t) * Math.sin(t) * Math.sin(t)) + WIDTH / 2;
y = (int) (-13 * Math.cos(t) + 5 * Math.cos(2 * t) + 2 * Math.cos(3 * t) + Math.cos(4 * t)) + HEIGHT / 2;
g.fillOval(x, y, 5, 5);
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
drawHeart(g);
}
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(WIDTH, HEIGHT);
jFrame.add(new HeartDrawing());
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
}
}
```
希望您能喜欢这个代码!
阅读全文