直接上代碼
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() ;//重畫;
}
}
}