java画玫瑰花的代码
时间: 2023-10-14 18:31:24 浏览: 675
java 打印玫瑰
以下是用Java绘制玫瑰花的基本代码:
```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;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int centerX = width / 2;
int centerY = height / 2;
int r = Math.min(centerX, centerY) - 5;
g.setColor(Color.RED);
for (double i = 0; i < Math.PI * 2; i += 0.01) {
double x = r * Math.cos(6 * i) * Math.cos(i) + centerX;
double y = r * Math.cos(6 * i) * Math.sin(i) + centerY;
g.fillOval((int) x, (int) y, 2, 2);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rose");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Rose());
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
这个示例程序使用 Java Swing 绘制一朵玫瑰花,利用数学函数计算出每个点的位置,然后在屏幕上绘制出来。你可以根据需要进行修改和优化。
阅读全文