java樱花树的代码编写
时间: 2023-11-10 15:56:23 浏览: 96
可以利用Java的图形库(如Swing)来实现一个简单的樱花树效果。下面是一个基本的代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class SakuraTree extends JFrame {
private static final int WIDTH = 800; // 窗口宽度
private static final int HEIGHT = 600; // 窗口高度
private static final int NUM_BRANCHES = 5; // 树枝数量
private static final int MAX_BRANCH_LENGTH = 150; // 最长树枝长度
private static final int MIN_BRANCH_LENGTH = 50; // 最短树枝长度
private static final int MAX_ANGLE = 45; // 树枝最大角度
private static final int MIN_ANGLE = 20; // 树枝最小角度
public SakuraTree() {
setTitle("Sakura Tree");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
drawTree(g, WIDTH / 2, HEIGHT - 50, -90, 100);
}
private void drawTree(Graphics g, int x1, int y1, double angle, int length) {
if (length < MIN_BRANCH_LENGTH) {
return;
}
int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * length);
int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * length);
g.setColor(Color.BLACK);
g.drawLine(x1, y1, x2, y2);
Random random = new Random();
int numBranches = NUM_BRANCHES;
if (length == MAX_BRANCH_LENGTH) {
numBranches++; }
for (int i = 0; i < numBranches; i++) {
double branchAngle = angle + random.nextInt(MAX_ANGLE - MIN_ANGLE + 1) + MIN_ANGLE;
int branchLength = length * (random.nextInt(70) + 30) / 100;
drawTree(g, x2, y2, branchAngle, branchLength);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SakuraTree());
}
}
```
可以通过运行以上代码来查看樱花树的效果。请确保已经安装并配置好Java开发环境。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)