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() ;//重画;
        }
    }
}



  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值