java实现雪花飘落效果(附完整源码)
时间: 2023-11-11 08:03:24 浏览: 107
以下是Java实现雪花飘落效果的完整源码:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Snowfall extends JPanel implements Runnable {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int NUM_OF_SNOWFLAKES = 100;
private static final int DELAY = 25;
private ArrayList<Snowflake> snowflakes;
public Snowfall() {
snowflakes = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < NUM_OF_SNOWFLAKES; i++) {
int x = rand.nextInt(WIDTH);
int y = rand.nextInt(HEIGHT);
int speed = rand.nextInt(5) + 1;
snowflakes.add(new Snowflake(x, y, speed));
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
for (Snowflake s : snowflakes) {
g.fillOval(s.getX(), s.getY(), 5, 5);
}
}
@Override
public void run() {
while (true) {
for (Snowflake s : snowflakes) {
s.move();
}
repaint();
try {
Thread.sleep(DELAY);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
private class Snowflake {
private int x;
private int y;
private int speed;
public Snowflake(int x, int y, int speed) {
this.x = x;
this.y = y;
this.speed = speed;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move() {
Random rand = new Random();
int newX = x - speed + rand.nextInt(3);
int newY = y + speed + rand.nextInt(3);
if (newX < 0 || newX > WIDTH || newY > HEIGHT) {
newX = rand.nextInt(WIDTH);
newY = rand.nextInt(HEIGHT / 4);
}
x = newX;
y = newY;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Snowfall");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
Snowfall snowfall = new Snowfall();
frame.add(snowfall);
frame.setVisible(true);
new Thread(snowfall).start();
}
}
```
运行这个程序,你将会看到一个简单的窗口,其中有100个雪花飘落。在这个程序中,我们首先在构造函数中创建一些雪花对象,这些对象具有随机的位置和速度。然后,在重绘方法中,我们遍历所有的雪花对象,并绘制它们。在运行方法中,我们不断移动每个雪花对象,并重新绘制窗口。
阅读全文