Java中的玫瑰花代码如何写
时间: 2023-07-15 19:12:20 浏览: 602
Java中的玫瑰花代码可以使用Graphics类中的方法实现,具体代码如下:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Rose extends JPanel {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
public Rose() {
this.setBackground(Color.BLACK);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
double k = 6;
for (double t = 0; t < Math.PI * 2; t += 0.01) {
double r = 200 * Math.cos(k * t);
int x = (int) (r * Math.cos(t)) + WIDTH / 2;
int y = (int) (r * Math.sin(t)) + HEIGHT / 2;
g.fillOval(x, y, 2, 2);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rose");
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(new Rose());
frame.setVisible(true);
}
}
```
运行该代码,可以看到在窗口中绘制出了一朵玫瑰花。