成果图
SnowJFrame类
package cn.edu.sqc.zzx;
import javax.swing.*;
public class SnowJFrame extends JFrame{
public static void main(String[] args) {
SnowJFrame asj = new SnowJFrame();
}
public SnowJFrame(){
this.setTitle("雪花飘落");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setLocationRelativeTo(null);
SnowJPanel sjp = new SnowJPanel();
this.add(sjp);
Thread thread = new Thread(sjp);
thread.start();
this.setVisible(true);
}
}
SnowJPanel类
package cn.edu.sqc.zzx;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class SnowJPanel extends JPanel implements Runnable {
int[] x = new int[300];
int[] y = new int[300];
int[] a = new int[300];
public int random(int a){
return (int)(Math.random()*a);
}
public SnowJPanel(){
for (int i = 0; i < 100; i++) {
x[i] = new Random().nextInt(800) + 1;
y[i] = new Random().nextInt(600) + 1;
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
setBackground(Color.black);
g.setColor(Color.white);
for (int i = 0; i < 300; i++) {
g.drawString("*",x[i],y[i]);
for (int j = 0; j < a[i]; j++) {
g.drawString("*",x[i],600 - j*3);
}
}
g.fillOval(530,60,50,50);
g.setColor(Color.black);
g.fillOval(550,60,50,50);
}
@Override
public void run() {
while(true){
for (int i = 0; i < y.length; i++) {
if(y[i]<=600){
y[i] ++;
}else{
a[i] ++;
y[i] = 0;
}
}
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}