Java窗体利用多线程实现雪花飘落动画

成果图

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();
            }
        }
    }
}
经验分享 程序员 微信小程序 职场和发展