纯Java代码实现流星划过天空
废话不多说了,直接给大家贴java代码了。
importjava.awt.Color;
importjava.awt.Graphics;
importjava.awt.image.BufferedImage;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
publicclassMeteorFlyextendsJFrame{
finalintMAX=;//(~)流星的个数
finalintSLEEP=;//流星飞行的速度(数值越大,速度越慢)
finalintCOLORLV=;//(~)色阶(可改变光晕大小)
finalStringCOLOR=null;//("#"~"#ffffff")光晕颜色(如果不填或null,则为默认颜色)
finalintSIZE=;//(~)流星大小
privateMyPanelpanel;
publicMeteorFly(){
panel=newMyPanel();
this.getContentPane().add(panel);
this.setSize(,);//创建窗体
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
publicstaticvoidmain(String[]args){
newMeteorFly();
}
classMyPanelextendsJPanelimplementsRunnable{
Meteorp[];
intAppletWidth,AppletHeight;
BufferedImageOffScreen;
GraphicsdrawOffScreen;
ThreadpThread;
publicMyPanel(){
setBackground(Color.black);//窗体初始化
AppletWidth=;
AppletHeight=;
p=newMeteor[MAX];
for(inti=;i<MAX;i++)
p[i]=newMeteor();
OffScreen=newBufferedImage(AppletWidth,AppletHeight,
BufferedImage.TYPE_INT_BGR);
drawOffScreen=OffScreen.getGraphics();
pThread=newThread(this);
pThread.start();
}
@Override
publicvoidpaintComponent(Graphicsg){
//TODOAuto-generatedmethodstub
super.paintComponents(g);
g.drawImage(OffScreen,,,this);
}
@Override
finalpublicvoidrun(){
while(true){
//drawOffScreen.clearRect(,,AppletWidth,AppletHeight);//
//清屏
for(inti=;i<MAX;i++){
drawOffScreen.setColor(p[i].color);//RGB颜色
drawOffScreen.fillOval(p[i].x,p[i].y,SIZE,SIZE);
p[i].x+=p[i].mx;
p[i].y+=p[i].my;
//if(p[i].x>AppletWidth||p[i].y>AppletHeight){
//p[i].reset();
//}
intx=p[i].x;
inty=p[i].y;
intR=p[i].color.getRed();//提取颜色
intG=p[i].color.getGreen();
intB=p[i].color.getBlue();
while(true){
if(R==&&G==&&B==){
break;
}
R-=COLORLV;//尾部颜色淡化
if(R<){
R=;
}
G-=COLORLV;
if(G<){
G=;
}
B-=COLORLV;
if(B<){
B=;
}
Colorcolor=newColor(R,G,B);
x-=p[i].mx;//覆盖尾部
y-=p[i].my;
drawOffScreen.setColor(color);
drawOffScreen.fillOval(x,y,SIZE,SIZE);
}
if(x>AppletWidth||y>AppletHeight){//流星飞出窗口,重置流星
p[i].reset();
}
}
repaint();
try{
Thread.sleep(SLEEP);
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
}
classMeteor{//流星类
intx,y;//流星的位置
intmx,my;//下落速度
Colorcolor;//流星颜色
publicMeteor(){
reset();
}
publicvoidreset(){
intrand=(int)(Math.random()*);//随机生成流星出现位置
if(rand>){
x=(int)(Math.random()*);
y=;
}else{
y=(int)(Math.random()*);
x=;
}
mx=(int)(Math.random()*+);//随机生成下落速度和角度
my=(int)(Math.random()*+);
if(COLOR==null||COLOR.length()==){
color=newColor(
//随机颜色
(newDouble(Math.random()*)).intValue()+,
(newDouble(Math.random()*)).intValue()+,
(newDouble(Math.random()*)).intValue()+);
}else{
color=Color.decode(COLOR);
}
}
}
}
以上代码就是本文给大家讲述的纯Java代码实现流星划过天空,希望本文分享能够给大家带来意想不到的收获。