eclipse 雪花代码
时间: 2023-09-30 19:08:17 浏览: 70
下面是一个用Java编写的Eclipse雪花代码:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SnowFlake extends JPanel {
private final static int WIDTH = 640;
private final static int HEIGHT = 480;
private final static int MAX_LENGTH = 100;
private final static int MIN_LENGTH = 10;
private final static int MAX_ANGLE = 360;
private final static int MAX_BRANCHES = 4;
private static Random random = new Random();
public static void main(String[] args) {
JFrame frame = new JFrame("SnowFlake");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.getContentPane().add(new SnowFlake());
frame.setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, WIDTH, HEIGHT);
drawSnowFlake(g2d, WIDTH / 2, HEIGHT / 2, MAX_LENGTH, 0);
}
private static void drawSnowFlake(Graphics2D g2d, int x, int y, int length, int angle) {
if (length < MIN_LENGTH) {
return;
}
for (int i = 0; i < MAX_BRANCHES; i++) {
double branchAngle = angle + i * MAX_ANGLE / MAX_BRANCHES;
int branchLength = length - random.nextInt(length / 2);
int endX = x + (int) (branchLength * Math.cos(Math.toRadians(branchAngle)));
int endY = y + (int) (branchLength * Math.sin(Math.toRadians(branchAngle)));
g2d.draw(new Line2D.Double(x, y, endX, endY));
drawSnowFlake(g2d, endX, endY, branchLength, (int) branchAngle);
}
}
}
```
这个程序会在窗口中绘制一个雪花,雪花会随机生成分支并递归绘制。运行程序后,您将看到类似于以下图像的雪花:
![SnowFlake](https://i.imgur.com/4G4ln4A.png)
阅读全文