java满天星系列 1 ——几百颗动态多彩星星闪动效果

直接上代码
package day0425;

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class myJFrame1  extends JFrame{

    public  myJFrame1(){

        this.setSize(800,600) ;     //设置窗体大小
        myJPanel mj = new myJPanel() ;
        mj.setBackground(Color.BLACK);
        this.setBackground(Color.BLACK) ;
//创建一个面板
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        Thread t = new Thread(mj) ;  //生成一个线程类
        t.start() ;                 //启动线程
        Container cn = this.getContentPane() ;    //创建一个容器
        cn.add(mj) ; //将面板添加到容器中
        this.setVisible(true);
    }


    public static void main(String[] args) {
        myJFrame1 yt = new myJFrame1() ;
    }
}


//自定义一个类继承自JPanel并实现Runnable接口
class myJPanel extends JPanel implements Runnable{
    final int shuliang = 400  ; //设置星星数量
    int x[] = new int[shuliang] ;
    int y[] = new int[shuliang] ;
    Color ccc[] = new Color[shuliang] ;//用于设置星星的背景色.
    public myJPanel(){
        for(int i = 0 ; i < shuliang ; i ++){
            x[i] = (int)(Math.random()*800) ;//随机产生400个X轴的坐标点
            y[i] = (int)(Math.random()*600) ;// 随机产生400个Y轴的坐标 点
        }
        for(int i = 0 ; i < 400 ; i ++) {
            ccc[i] = new Color((int)(Math.random()*0xffffff)) ;// 随机产生400背景颜色
        }
    }
    //重写paint方法
    public void paint(Graphics g) {
        g.clearRect(0 , 0 , 800 , 600) ;  //清除屏幕的内容
        for(int i = 0 ; i < shuliang ; i ++){
            g.setColor(ccc[i]) ; //设置400个星星的背景颜色
            if((int)(Math.random()*150) != 0){
                g.drawString("*" , x[i] , y[i]) ;//将星星画出
            }
        }
    }

    //run方法  线程启动时调用
    public void run(){
        while(true){
            try{Thread.sleep(20) ;}catch(Exception e){}
            this.repaint() ;//重画;
        }
    }
}



猜你喜欢

转载自blog.csdn.net/libinxie/article/details/80072770