用 java写个生长的梅花
时间: 2024-03-05 17:53:09 浏览: 7
好的,以下是用Java实现生长的梅花的代码:
```
import java.awt.*;
import javax.swing.*;
public class MeiHua extends JFrame {
public MeiHua() {
setTitle("生长的梅花");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
getContentPane().setBackground(Color.BLACK);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(1));
drawMeiHua(g2d, 300, 300, 100, Math.PI / 2, 0.5, 0.8, 5);
}
private void drawMeiHua(Graphics2D g, double x, double y, double l, double angle, double k1, double k2, int depth) {
if (depth == 0) {
return;
}
double x1 = x + l * Math.cos(angle);
double y1 = y - l * Math.sin(angle);
g.setColor(Color.WHITE);
g.drawLine((int) x, (int) y, (int) x1, (int) y1);
drawMeiHua(g, x1, y1, l * k1, angle - Math.PI / 4, k1, k2, depth - 1);
drawMeiHua(g, x1, y1, l * k2, angle + Math.PI / 4, k1, k2, depth - 1);
}
public static void main(String[] args) {
new MeiHua();
}
}
```
这个程序实现了一个递归的梅花绘制函数 `drawMeiHua`,通过不断递归调用这个函数,可以实现梅花的生长。在绘制梅花时,使用了数学上的正弦余弦函数,来计算梅花的生长方向和长度。最后在 `paint` 函数中调用 `drawMeiHua` 来绘制整个梅花。运行程序后,可以看到一个生长的梅花在窗口中逐渐展开。