java程序設(shè)計從入門到精通-300個編程實(shí)例_第1頁
java程序設(shè)計從入門到精通-300個編程實(shí)例_第2頁
java程序設(shè)計從入門到精通-300個編程實(shí)例_第3頁
java程序設(shè)計從入門到精通-300個編程實(shí)例_第4頁
java程序設(shè)計從入門到精通-300個編程實(shí)例_第5頁
免費(fèi)預(yù)覽已結(jié)束,剩余34頁可下載查看

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

14JavaApplet難度指占用時Java32223343難度指占用時Java3222334333圖像文4243Applet的53實(shí)例 【實(shí)例描述向大家一一展示這些動態(tài)效果。首先來看文字近效果,它表現(xiàn)為隨著文字不斷變大,給人14.1所示。14.1【實(shí)現(xiàn)過程publicclassWordsToLargeextendsAppletimplementsRunnable{privateImagemyImage;privatepublicclassWordsToLargeextendsAppletimplementsRunnable{privateImagemyImage;privateGraphics//定對//定義Graphics對privateFont //定義Font對privateString //privateThread //定義一個Thread對privateint //定義一個intpublicvoidinit Applet小程序初始myImage //創(chuàng)建Image圖像對myGraphic=myString="JavaApplet小應(yīng)用程序 //需要變化的文本內(nèi)fontnewFont("華文行楷F(xiàn)ont.BOLD,}publicvoidstart //if(mythread==null)mythread=new //啟動線}}publicvoidupdate(Graphicsg //重新調(diào)用paint方}publicvoidpaint(Graphicsg //myGraphic.fillRect(0,0,getSize().width,fontnewFont("TimesRomanFont.BOLD //設(shè)置要變化文字的字體大小和顏FontMetricsfm=myGraphic.getFontMetrics(font);intfontHeight=fm.getHeight();intintbaseLine=getSize().height/2+fontHeight/2;w=fm.stringWidth(myString);w=(getSize().width-w)/2;myGraphic.drawString(myString,w,baseLine-=20);g.drawImage(myImage,0,0,this);}publicvoidrun //重寫Threadrun方while(true)if(fontSize>getSize().height)fontSize=0;try}catch(InterruptedExceptione)}}}}【代碼解析14.2所示的順序調(diào)用以下方法:Applet的初始化順 Applet的終止順start()方start()方init()方destroy()方stop()方paint()方14.2Javapaint()方stop()方法:當(dāng)WebHTML文件時,stop()方法就被調(diào)用,如在desoydesroy你應(yīng)該任何應(yīng)用程可能用的源。sop(方法總在esroy)之被調(diào)用。實(shí)例 【實(shí)例描述舞動的彩文也是網(wǎng)頁上常見的一種動態(tài)效果可以使用Applet程序在對文字進(jìn)行位置變化的同動感和美觀,讀者的閱讀積極性。具體的運(yùn)行效果如圖14.3所示。14.3【實(shí)現(xiàn)過程。用Applet中的Font類設(shè)置文字的字體和顏色,并通過update()方法實(shí)現(xiàn)文字的位置和速度控制代。publicpublicclassColorWordsextendsAppletimplementsRunnable{Stringstr=null;intd=inth=18;intv=Threadthread=char[]ch;intp=0;Imageimage;Graphicsgphics;Color[]color;privateFontf;privateFontMetricsfm;publicvoidinit(){str天行健,君子以自強(qiáng)不息this.setSize(500,200);ch=newchar[str.length()];ch=str.toCharArray();image=createImage(getSize().width,getSize().height);gphics=image.getGraphics();fnewFont("華文行楷F(xiàn)ont.BOLD,fm=getFontMetrics(f);floatcolor=newColor[str.length()];for(inti=0;i<str.length();i++){hue=((float)i)/((float)////////////設(shè)置Applet////////color[inewColor(Color.HSBtoRGB(hue0.8f1.0f));//}}publicvoidstart()if(thread==null)threadthread=new//}}publicvoidstop(){if(thread!=null)thread=}////}publicvoidrun()while(thread!=null){try{}catch(InterruptedExceptione)}}}publicvoidupdate(Graphicsg){intx,y;doublegphics.fillRect(0,0,getSize().width,getSize().height);p+=d;p%=for(inti=0;i<str.length();i++)angle=((p-i*d)%7)/4.0*////200////重寫update////x30fm.getMaxAdvance()*iintMath.cos(angle*h);//求xy80intMath.sin(angle* //求ygphics.setColor(color[(p+i)%str.length()]);gphics.drawChars(ch,i,1,x,y);}}publicvoidpaint(Graphicsg){g.drawImage(image,0,0,this);}}【代碼解析本例先來具體為大家講解init()方法的內(nèi)容其他幾種方法會在后面的例子中為大家一一講解。init()方法:AppletApplet的時候,對象會首先自動調(diào)用該方法,以完成必要的需要注意的是該方法只被調(diào)用一次。init()方法的方式如圖14.4所示。publicpublicvoid//創(chuàng)創(chuàng)創(chuàng)創(chuàng)//創(chuàng)創(chuàng)創(chuàng)創(chuàng)}圖14.4init()方法的方【知識擴(kuò)展publicvoidupdate(Graphicsg)}publicvoidpaint(Graphicsg){}AWTupdate()方法。這update()的方法是先用默認(rèn)的背景顏色填充小應(yīng)用程序窗口,再調(diào)用paint()方法。如果你在填充背景時用的顏色與paint()方法中使用的update()publicvoidupdate(Graphicsg)}publicvoidpaint(Graphicsg){}實(shí)例 文字的3D效【實(shí)例描述目前3D技術(shù)已經(jīng)形成一股潮流,不但、紛紛采用3D效果創(chuàng)建更完美的畫面,就連14.5所示。14.5文字的3D效【實(shí)現(xiàn)過程EclipseWords3DWords3D.javapublicclassWords3DextendsJAppletimplementsRunnable{privateImage ImageprivateImage Image變privateGraphics 繪圖對privateThreadthread 線privateMediaTracker privateintheight int變privateString String變量privateFont publicvoidinit Applet, //設(shè)置初始大width //得到容器的height //獲取容器的 //設(shè)置容器的背景imagecreateImage(widthheight);//根據(jù)當(dāng)前的寬和高創(chuàng)建一個圖text //String變量text賦Stringstr= //創(chuàng)建一個有初始值的String變if(str!=text=str; //str的值不為空的前提下,將str的值賦給textfont=newFont("華文行楷",Font.BOLD,50);//創(chuàng)建一個Font對象tracker=newMediaTracker(this); //創(chuàng)建一個MediaTracker對象tracker.addImage(image,0); //將image加載到tracker中try{ //等待加載Id0}catch(InterruptedExceptione)}image_1createImage(width //根據(jù)當(dāng)前的寬和高創(chuàng)建一個圖gp //根據(jù)圖像image_1,獲得Graphics對}publicvoidstart //啟動線if(thread==null)thread=newThread(this);}}publicvoidrun //運(yùn)行線intx //設(shè)置繪制圖像的X坐intyheight //設(shè)置繪制圖像的Y坐intRG //設(shè)置RGB //while(threadnull ////隨機(jī)生成ColorR=(int)(255*Math.random());G=(int)(255*Math.random());B=(int)(255*Math.random());try{ //線程休眠2000毫}catch(InterruptedExceptionex)} //gp.fillRect(00width,height);// //for(inti=0;i<10;i++)gp.setColor(newColor((255-(0+R)*i/10),(255-(0+*i/10),(255-(0+B)*i/gp.drawString(textxiyi);//stringtry{////60}catch(InterruptedExceptione)}}}}publicvoidpaint(Graphicsg //g.drawImage(image1,0,0,}}【代碼解析start()Applet程序的網(wǎng)頁又返回時,start()方法。start()init()init()start()卻在每一次HTML文檔被顯示在屏幕上時都被調(diào)用。因此,如果用戶離開一個網(wǎng)頁之后重新進(jìn)入時,小應(yīng)用程序就會從start()開始重新執(zhí)行。start()方法的方式如圖14.6所示。publicpublicvoid//創(chuàng)創(chuàng)創(chuàng)//創(chuàng)創(chuàng)創(chuàng)}圖14.6start()方法的方【知識擴(kuò)展理字體。JavaFont類中的方法來實(shí)現(xiàn)。Font類中的方法很多,14-1列出了其中的一些常用的方法。14-1Font方法方法說方drawString(Stringstr,intx,intdrawChars(chardata[],intoffset,intx,intdrawBytes(bytedata[],intoffset,intx,intsetFont(Font設(shè)置字實(shí)例 【實(shí)例描述。在網(wǎng)頁中也經(jīng)常會看到許多很漂亮的字體閃爍可以不斷地改變文字文字背景的顏色以及頁面的友。具體的運(yùn)行效果如圖14.7所示。。14.7【實(shí)現(xiàn)過程publicclassWordsExpansionextendsAppletimplementsRunnableprivateImagemyImage;privateGraphicsmyGraphic;privateintpublicclassWordsExpansionextendsAppletimplementsRunnableprivateImagemyImage;privateGraphicsmyGraphic;privateintwidth=0,height=0;privateStringwords;privateThreadImage圖象對//定義文本內(nèi)privateintxPosition0yPosition0myHeight;//定義x和y坐標(biāo)privateinttimes=privateFontfont;publicvoidinit()////初始化Applet小程{this.setSize(300,fontnewFont("華文行楷F(xiàn)ont.BOLD30);width=300;height=200;myHeight=height/3;yPosition=wordsJavamyImage=createImage(width,height);myGraphic=myImage.getGraphics();}publicvoid //啟動Applet{if(mythread==null)mythread=newThread(this);}}publicvoidupdate(Graphics //更新組{}publicvoidpaint(Graphics //繪制組{g.drawImage(myImage,0,yPosition,width,myHeight,}publicvoid //{try

while(true)yPosition=0;myHeight=height;myGraphic.fillRect(0,0,width,height);if(times==0){for(inti=width;i>=0;i--){myGraphic.fillRect(i,height/3,width,height/10);}}elseif(times==1){for(inti=0;i<=width;i++){myGraphic.fillRect(0,height/3,i,height/10);}}}yPosition=height/3;myHeight=height/for(inti=height/3;i>=0;i--){xPosition=0;myHeight=myHeight+iftimes {myGraphic.fillRect(0,0,width,height);myGraphic.drawString(words,10,35);elseiftimes {myGraphic.fillRect(0,0,width,height);myGraphic.drawString(words,10,35);times=}}}}catch(InterruptedExceptione)}}}【代碼解析paint()就被調(diào)用。paint()Graphics類型的參數(shù)。這個參數(shù)包含了圖像上下文,描述了小應(yīng)用程序所運(yùn)行的環(huán)境。在需要對小應(yīng)用程序進(jìn)行輸出時,這個上下文將被用到。paint()方法的方式如14.8所示。}圖14.8paint()方法的方【知識擴(kuò)展Color通過RGB的值顏色14-2所示。14-2有關(guān)字體顏色的方法說方方法說Color(intR,intG,intsetColor(ColorsetBackground(Color實(shí)例 【實(shí)例描述這種效果主要是為了更好地突出,營造一種“閃亮登場”的感覺。也可以使用Applet程序來實(shí)14.9所示。14.9【實(shí)現(xiàn)過程publicclassLightScanextendsAppletimplementsRunnable{privateStringmyText;privateFontfont;privateintfontSize;privateThreadprivateintpublicclassLightScanextendsAppletimplementsRunnable{privateStringmyText;privateFontfont;privateintfontSize;privateThreadprivateintspotPosition=100;privateintmyTextSize=40;文本對//privateintmyTextWidth //privateintfontHeight,baseLine,publicvoid //{myText="我是世界第一 //在小程序中需要顯示的文本對fontSize //font=newFont("華文琥珀",Font.BOLD, //創(chuàng)建Font對FontMetricsfm //獲取FontMetrics字體規(guī)格對象fontHeight=baseLine=getSize().height/2+fontHeight/3;myTextWidth=fm.stringWidth(myText);w=fm.stringWidth(myText);w=(getSize().width-w)/2;spotPosition=w; //設(shè)置小程序的背景色為黑}publicvoidstart()if(mythread==null)mythreadnew // //}}publicvoidstop() //停止運(yùn)行線mythread=}publicvoid //運(yùn)行線{while(true) //try //線程休catch(InterruptedExceptione)}}}publicvoidupdate(Graphics //更新組{}//利用clipRect()方法,每次調(diào)用顯示方法paint()時//先用紅色的筆畫一遍文字,再用白色在裁剪區(qū)中畫一遍文publicvoidpaint(Graphicsg){g.drawString(myTextw //g.clipRect(spotPosition0myTextSizegetSize().height);//設(shè)置裁剪區(qū)g.drawString(myTextw //spotPositionspotPositionspotPosition1myTextWidth100);//}}【代碼解析start()stop()方法,init()方法,它可以在一個生命周期中多次被調(diào)用。如果Applet程序不包含動畫、聲音文件時,不需要重載該方法。stop()方法的聲14.10所示。publicpublicvoidstop(){}Applet圖14.10stop()方法的方,與init()方法相同,該方法在一個生命周期中只能執(zhí)行一次。瀏覽器正常關(guān)閉時調(diào)用該方法資Applet派生類可以重寫該方法,完成特定的操作。destroy()方法的方式如圖14.11所示。,publicpublicvoiddestroy(){}創(chuàng)Applet圖14.11destroy()方法的方實(shí)例 簡易放大【實(shí)例描述使用編輯查看時,通常都具有的放大和縮小功能。本例中創(chuàng)建一個簡易的放大鏡來實(shí)現(xiàn)對的局部放大,使細(xì)節(jié)更加清晰。具體的運(yùn)行效果如圖14.12所示。圖14.12簡易放大【實(shí)現(xiàn)過程publicclassZoomImageextendsAppletimplementsMouseMotionListenerGraphicsg;Imageimage;Imageback_Image;Stringname;MediaTrackertracker;intGlass_X=0,Glass_Y=intGlass_W=100,Glass_HpublicclassZoomImageextendsAppletimplementsMouseMotionListenerGraphicsg;Imageimage;Imageback_Image;Stringname;MediaTrackertracker;intGlass_X=0,Glass_Y=intGlass_W=100,Glass_H=100;intwidth,height;publicvoidinit(){this.setSize(370,500);g=getGraphics();name="ty.jpg";tracker=newMediaTracker(this);backImage=getImage(getimage=createImage(250,100);Graphicsoffg=Graphics對Image對象Image對象String對象////放大鏡寬度、高背//初始化//加Base(),//offg.drawImage(backImage,0,0, //添加鼠標(biāo)事件偵}publicvoidmouseDragged(MouseEvente)}publicvoidmouseMoved(MouseEvente)//鼠標(biāo)拖拽事件處//處理鼠標(biāo)移動事reprintGlass(Glass_XGlass_Ye.getXe.getY());//Glass_X=e.getX();GlassY=if(Glass_X>(width-Glass_W/GlassX=width-GlassW/2;if(GlassY>(height-GlassH/2))GlassY=height-GlassH/2;//設(shè)置放大鏡的當(dāng)前位//若放大鏡溢出applet則進(jìn)行調(diào)//}voidprintGlass()Graphicstemp=g.create(); g的一個實(shí)例temp.clipRect(Glass_XGlass_YGlass_WGlass_H);//為temp限制一個矩形區(qū)域temp.drawImage(backImage,-GlassX,-GlassY,width*2,height*2, //輸出放大后的圖g.setColor(Color.black);//g.drawRect(Glass_XGlass_YGlass_W1Glass_H1);//}voidreprintGlass(intXintYintnew_Xintnew_Y){//清除已經(jīng)畫過的矩形框和放大的圖Graphicstemp=if(newX<=X&&newY<=Y)temp.clipRect(new_X,new_Y+Glass_H,Glass_W+X-new_X,newnewY);temp.drawImage(image,0,0,null);temp=g.create();temp.clipRect(newX+GlassW,newY,X-newX,GlassH+newY);temp.drawImage(image,0,0,null);}}publicbooleanimageUpdate(Imageimg,intinfoflags,intx,inty,intinth){ //判斷infoflags參數(shù)是否已完全加載了圖像,是則返回false;否則返回trueif(infoflags==ALLBITS) //ALLBITS指示現(xiàn)在已完成了一幅以前繪制的靜態(tài)圖width=backImage.getWidth(this);height=backImage.getHeight(this);image=createImage(width+GlassW/2,height+GlassH/2);Graphicsoffg=image.getGraphics();offg.fillRect(0,0,width+GlassW/2,height+GlassH/2);offg.drawImage(backImage,0,0,this);returnfalse;}return}publicvoidpaint(Graphicsg)g.drawImage(back_Image00 // //}}【代碼解析個步驟:第一步裝載圖像文件,第二步顯示圖像。AppletURL描述。具體方式如圖14.13所示。publicImagegetImage(URLurl圖14.13圖像文件加載的方實(shí)例 【實(shí)例描述14.14所示。14.14帶波紋的水面倒【實(shí)現(xiàn)過程publicclassAgitatedWaterextendsAppletimplementsRunnableThreadthread=null;privateGraphicsg,inv_g;privatepublicclassAgitatedWaterextendsAppletimplementsRunnableThreadthread=null;privateGraphicsg,inv_g;privateImageimage,invimage;privateintinv;privateintimage_W=2,image_H=2;privatebooleanload_Flag=false;privatefinalintfre=14;privateStringpicture_name=publicvoidinit()線//定義繪制正常圖像和倒立后圖像的Graphics對image用于載入正常圖像,invimage//應(yīng)用于形成倒立影象的變//定義裝//是否完//定義水紋波動的頻率,數(shù)值越//定名//初始化picture_name }publicvoidpaint(Graphicsg)if //如果已經(jīng)載 ,則返if(invimage!=null){ //輸出倒影g.drawImage(invimage,(-inv*imageW),imageH,this);g.drawImage(invimagefreinv)*imageW),imageHthis);}g.drawImage(image01 //輸出正}publicvoidstart(){ //啟動applet,創(chuàng)建并啟動線程if(thread==null){thread=newThread(this);}}publicvoidrun //啟動線inv= //加g=MediaTrackerimageTracker=newMediaTracker(this);image=getImage(this.getCodeBase(),picturename);imageTracker.addImage(image,0);tryload_Flag=!imageTracker.isErrorAny();//檢 }catch(InterruptedExceptione)}image_W= imageH=image.getHeight(this);this.setSize(imageW+1,imageH*2-19); //生成倒 //重新輸出while(true){try{if(!loadFlag)if(invimage!=null)g.drawImage(invimage,(-inv*imageW),imageH,this);g.drawImage(invimage,((fre-inv)*imageW),imageH,this);}g.drawImage(image,0,-1,this);if(++inv==fre)inv=0;}catch(InterruptedExceptione){}}}publicvoidcreatWater ImageImageback=createImage(imageW+3,imageH+2);Graphicsgraphics=back.getGraphics();intphase=0;intx,y;doublep1;graphics.drawImage(image,0,1,this);for(inti=0;i<(imageH>>1);i++)graphics.copyArea(0,i,imageW,1,0,imageH-graphics.copyArea(0,imageH-1-i,imageW,1,0,-imageH+1+(i<<1));graphics.copyArea(0,imageH,imageW,1,0,-1-i);}invimage=createImage((fre+1)*imageW+20,imageH+2);invg=invimage.getGraphics();invg.drawImage(back,fre*imageW,0,this);for(phase=0;phase<fre;phase++){p1=2*Math.PI*(double)phase/(double)fre;x=(fre-phase)*imageW;for(inti=0;i<imageH;i++){y=(int)((imageH/14)((double)i+Math.sin((double)((imageH/14)*(imageH-/(double)(i+1)+p1)/(double)imageif(i<-invg.copyArea(fre*imageW,i,imageW,1,-x,invg.copyArea(fre*imageW,i+y,imageW,1,-x,-}}graphics.drawImage(image,0,1,this);image=back;}}【代碼解析有關(guān)四種顯示圖像的方法,其輸入圖像代碼寫在paint()方法中。具體的方法及方法說明如表14-14-3圖形處理方法及方法說方方法說booleandrawImage(Imageimg,intx,inty,ImageObserverbooleandrawImage(Imageimg,intx,inty,Colorbgcolor,ImageObserverobserver)booleandrawImage(Imageimg,intx,int,intwidth,intheight,ImageObserverobserver)booleandrawImage(Imageimg,intx,int,intwidth,intheight,,Colorbgcolor,ImageObserverobserver)實(shí)例 【實(shí)例描述在重大節(jié)日和慶典國人往往會通過燃放美麗的煙火來增加氣氛。美麗的煙火那曇花一現(xiàn)的美麗相信也必定深深埋藏在讀者的中本例使用JavaApplet小程序?qū)崿F(xiàn)夜空中璀璨的煙火示14.15所示。14.15夜空中璀璨的煙【實(shí)現(xiàn)過程使用Image和Graphics類實(shí)現(xiàn)效果。代碼如下所示:publicpublicclassMissileDemoextendsAppletimplementsRunnablepublicintspeed,variability,MaxNumber,MaxEnergy,MaxPatch,MaxLength,G;publicStringsound;privateintwidth,height;privateThreadthread=null;privateBeaClassDemobcd[];publicvoidinit(){intthis.setSize(400,400);width=getSize().width-1;height=getSize().height-1;speed=30;variability=Max_Number=MaxEnergy=width+50;Max_Patch=80;Max_Length=G=//////創(chuàng)建BeaClassDemo類數(shù)組Applet//////////bcd=newBeaClassDemo[Max_Number];//初始化BeaClassDemofor(i=0;i<MaxNumber;bcd[inewBeaClassDemo(widthheightG);//創(chuàng)建BeaClassDemo}publicvoidstart //啟動線if(thread==null)thread=newThread(this);}}publicvoidstop //停止線if(thread!=null){thread=}}publicvoidrun(){inti;intE=(int)(Math.random()*MaxEnergy*3/4)+MaxEnergy/4+boolean //Graphicsg=getGraphics();URLu=null;while(true){try{thread.sleep(1000/}catch(InterruptedExceptionx)}sleep=for(i=0;i<MaxNumber;i++)sleep=sleep&&bcd[i].sleep;if(sleep&&Math.random()*100<variability)E=(int)(Math.random()*MaxEnergy*3/4)+MaxEnergy/+}for(i=0;i<MaxNumber;i++)if(bcd[i].sleep&&Math.random()*MaxNumber*L<1){bcd[i].init(E,P,L,S);}}}}publicvoidpaint(Graphicsg){ //繪制組件 //設(shè)置背景顏色為黑g.fillRect(0,0,width+1,height+1); //根據(jù)參數(shù)畫矩形}}classBeaClassDemo{publicbooleansleep=true;privateintenergy,patch,length,width,height,G,Xx,Xy,Ex[],Ey[],x,y,Red,Blue,Green,privateRandom Random類對publicBeaClassDemo(intaintbintg //類BeaClassDemo的構(gòu)造方width=a;height=b;G=g;}publicvoidinit(inteintpintl,longseed //intenergy //賦值運(yùn)patch=p;length=//創(chuàng)建一個 random=newExnew //初始化int數(shù)組ExEynew //初始化int數(shù)組Ey//隨機(jī)生成不透明的sRGB顏色Red=(int)(random.nextDouble()*128)+128;Blue=(int)(random.nextDouble()*128)+128;Green=(int)(random.nextDouble()*128)+128;Xx=(int)(Math.random()*width/2)+width/4;Xy=(int)(Math.random()*height/2)+height/4;for(i=0;i<patch;i++){Ex[i]=(int)(Math.random()*energy)-energy/Ey[i]=(int)(Math.random()*energy*7/8)-energy/}}publicvoidstart(){t=0;sleep=}publicvoidshow(Graphicsg //輸if //如果休眠狀態(tài)為if(t<length){inti,c;doubles;Colorcolor;c=(int)(random.nextDouble()*64)-32+Red;if(c>=0&&c<256)Red=color=newColor(Red,Blue,Green);for(i=0;i<patch;i++){s=(double)t/100;x=(int)(Ex[i]*s);y=(int)(Ey[i]*s-G*s*s);g.drawLine(Xx+x,Xy-y,Xx+x,Xy-y);if(t>=length/2){intfor(j=0;j<2;j++)ss=(double)((t-length/2)*2+j)/100;x=(int)(Ex[i]*s);y=(int)(Ey[i]*s-G*s*s);g.drawLine(Xx+x,Xy-y,Xx+x,Xy-}}}elsesleep=}}}【代碼解析Graphics類提供基本的幾何圖形繪制方法,主要有:畫線段,畫矩形,畫圓,畫帶顏色的圖形,畫14-4所示。14-4Graphics方方法說drawLine(intx1,inty1,intx2,intdrawRect(intx,inty,intwidth,intfillRect(intx,inty,intwidth,intdraw3DRect(intx,inty,intwidth,intheight,booleanfill3DRect(intx,inty,intwidth,intheight,booleandrawOval(intx,inty,intwindth,intfillOval(intx,inty,intwindth,int圓drawArc(intx,inty,intwidth,intheight,intstartAngle,intfillArc(intx,inty,intwidth,intheight,intstartAngle,int實(shí)例 【實(shí)例描述14.16【實(shí)現(xiàn)過程publicclassBlindsextendsAppletimplementsRunnable{privateImageIMG[], privateMediaTracker ImageprivatepublicclassBlindsextendsAppletimplementsRunnable{privateImageIMG[], privateMediaTracker Imageprivateintwidthheightimage_count8image2 int類型的變privateThreadprivateintdelay=//定義int變量,初始值為privateintp,p_1[],p_2[],p_3[],p_4[],p_5[],p_6[],p_7[],p_A[],p_B[];publicvoidinit(){IMG=newImage[image_count];tracker=newMediaTracker(this);Strings="";for(inti=0;i<image_count;i++){s=(i+1)+".jpg";URLurl;try{url=newURL("file:"+IMG[i]=getImage(url);tracker.addImage(IMG[i],0);}catch(MalformedURLExceptione){}}try}catch(InterruptedExceptione)}width=height=////設(shè)置邊框的寬和//創(chuàng)建數(shù)組長度為image_count的Image數(shù)//創(chuàng)建MediaTracker對//創(chuàng)建URL對//創(chuàng)建Image對//將Image對象添加到tracker//等待加載ID0////pwidth* //寬和高的乘p_1new //創(chuàng)建長度為p的int數(shù)PixelGrabberPG1=newPixelGrabber(IMG[0],0,0,width,height,p1,0,//創(chuàng)建一個PixelGrabber對象,以便從指定的圖像中將像素矩形部分(xywh)try //請求Image開始傳遞像像}catch(InterruptedExceptionex)}image2=pA=newint[p];pB=newint[p];image=IMG[0];threadnew //創(chuàng)建線 //啟動線}publicvoidpaint(Graphics //繪制組{g.drawImage(image,0,0,}publicvoidupdate(Graphics //更新組{}publicvoid //運(yùn)行線{if(thread==null)thread=newThread(this);}while //控 {try //線程休眠delay毫秒image3=((image2+1)%image_count);//指向當(dāng)前 if(image2==0){System.arraycopy(p1,0,pA,0,//從下標(biāo)為0的p_1數(shù)組中 一個數(shù)組,存放到p_A數(shù)組中下標(biāo)為0的位置中,其數(shù)組長度為pSystem.arraycopy(p2,0,pB,0,p);image=createImage(newMemoryImageSource(width,p_A,0, //根據(jù)指定的圖 }while //控{for(inti=0;i<(int)(height/13);i++){try{ //線程休眠30毫for(intj=0;j<height;j+=(int)(height/13))forfor(intk=0;k<width;k++)pA[width*(j+i)+k]=p*j+ik];//}}}catch(InterruptedExceptione)}image=createImage(newMemoryImageSource(width,height,pA,0,width));}}image2=image3;}catch(InterruptedExceptione)}}}}【代碼解析在獲得圖像之后,需要使用java.awt.image.PixelGrabber包中的PixelGrabber方法將圖像PixelGrabberPG1=newPixelGrabber(IMG[0],0,0,width,height,p_1,0, 實(shí)例 【實(shí)例描述對于空間相信讀者都不感到陌生。一個友好的歡迎界面,不僅起到了宣傳產(chǎn)品的作用,而且標(biāo)識了應(yīng)用程序是否已經(jīng)成功啟動。本實(shí)例就是一個的空間歡迎頁面,用戶點(diǎn)擊頁面,頁面14.17所示。圖 【實(shí)現(xiàn)過程publicclassDesktop_WindowextendsJWindowimplementsRunnable{ThreadwaitThread;finalintfinalThreadpublicclassDesktop_WindowextendsJWindowimplementsRunnable{ThreadwaitThread;finalintfinalThreadpublicDesktop_Window(Stringimage_url,JFrameframe,intwaitTime){//建立一 JLabellabel=newJLabel(newImageIcon(image_url));getContentPane().add(label,BorderLayout.CENTER);//獲取屏幕的分辨率大DimensionscreenSize=DimensionlabelSize= //獲 大setLocation(screenSize.width2labelSize.width //screenSize.height/2-(labelSize.height///增加一個鼠標(biāo)事件處理器,如果用戶用鼠標(biāo)單擊了歡迎畫面,則關(guān)addMouseListener(newMouseAdapter()publicvoidmousePressed(MouseEvente){}rest=closerThreadnewThread //publicvoidrun()}waitThread=new////}publicstaticvoidmain(String[]args)throwsFileNotFoundException{JFrameframe=newJFrame(" frame.setDefaultCloseOperation(JFrame.DISPOSEONCLOSE);DesktopWindowdw=newDesktopWindow("D:/abc/ .jpg",frame,5000);}publicvoidrun()try //當(dāng)顯示了rest}catch(Exceptione){}}}【代碼解析DimensionDimensionscreenSize=addMouseListener(newaddMouseListener(newMouseAdapter()publicvoidmousePressed(MouseEvente){}}publicpublicvoidrun()}實(shí)例 【實(shí)例描述14.18雷電效果實(shí)【實(shí)現(xiàn)過程publicclassLightningextendsAppletimplementsRunnableprivateThreadthreadpublicclassLightningextendsAppletimplementsRunnableprivateThreadthread=null;privateintno_Light=0;privateintLight=1;privateint[]light;privateint[]array_1;privateint[]privateImageT_image,image;privateintdelay=3;publicvoidinit()StringimageName=applet//沒有閃電的標(biāo)志變量:0//有閃電的標(biāo)志變int型數(shù)組int型數(shù)組array_1int型數(shù)組Image變量T_image,////初始化image=getImage(getCodeBase(),//創(chuàng)建int型數(shù)組,定義其長度為getSize().heightlight=newint[getSize().height];array_1=newint[getSize().height];array_2=newT_imagethis.createImage(getSize().widthgetSize().height);//根據(jù)指定的參數(shù)創(chuàng)建一幅圖}publicvoidpaint(Graphicsg){inti,t;if(no_Light=={//沒有閃//g.fillRect(00getSize().widthgetSize().height);//g.drawImage(image00 //輸出} //{switch(Light){case1:g.setColor(newColor(240,255, //}g.fillRect(00getSize().widthgetSize().height);//tint0.6F* //輸出閃電圖for(i=1;i<getSize().height;i++)if(it //g.drawRect(light[i]-4,i,3,1);g.drawRect(light[i]+1,i,3,1);g.drawRect(light[i]-1,i,1,1);g.drawRect(light[i]+1,i,1,}switch(Light){case1:g.setColor(newColor(0,0, //藍(lán)色閃}g.drawLine(light[i],i,light[i-1],i-if(array_1[i0 //輸出閃電折g.drawLine(array1[i],i,array1[i-1],i-}if(array_2[i0 //輸出閃電折g.drawLine(array2[i],i,array2[i-1],i-}}g.drawImage(image,0,0,this); //輸出城市圖像city.gifLight=(int)((Math.random()*10)+1);}}voiddrawT_image(){ //調(diào)用paint()方法Graphicsg;g=Timage.getGraphics();}publicvoidstart(){ //啟動applet,創(chuàng)建并啟動線程if(thread==null){thread=newThread(this);}}publicpublicvoidstop()if(thread!=null){thread=}}voidcrea ight(){inti;intbs1,intbe1,////////light[0intMath.random*getSize().width);//array1[0]=light[0];array2[0]=bs1=(int)(Math.random()*getSize().height)+1;bs2=(int)(Math.random()*getSize().height)+be1=bs1+(int)(0.5*Math.random()*getSize().height)+1;be2=bs2+(int)(0.5*Math.random()*getSize().height)+1;for(i=1;i<getSize().height;i++){light[i]=light[i-1]+((Math.random()>0.5)?1:-1);array1[i]=light[i];array2[i]=}}publicvoidrun()Graphicsg;while(true){tryg=this.getGraphics();g.drawImage(Timage,0,0,this);////Thread.sleep((intdelay*1000*Math.random()));//no_Light=1; g=this.getGraphics();g.drawImage(Timage,0,0,this);no_Light=}catch(InterruptedExceptione){}////////1////}}}【代碼解析本例 首先初始化Applet小程序,加載image=getImage(getCodeBase(), Thread.sleep((int)(delay*1000* light[0]light[0]=(int)(Math.random()*getSize().width);array1[0]=light[0];array2[0]=bs1=(int)(Math.random()*getSize().height)+1;bs2=(int)(Math.random()*getSize().height)+be1=bs1+(int)(0.5*Math.random()*getSize().height)+be2=bs2+(int)(0.5*Math.random()*getSize().height)+實(shí)例 【實(shí)例描述Java14.19所示。圖14.19動態(tài)邊框示【實(shí)現(xiàn)過程 publicpublicclassDynamicBorderextendsAppletimplements//在applet中支持線程,需要實(shí)現(xiàn)Runnable{privateImagebimgfimgoffI ImageprivateGraphicsoffG Graphics對privateThreadthread privateMediaTracker privateintheightwidthX publicvoidinit()this.setSize(400, //初始化applet,加載背 StringimageName="龍貓.jpg";StringimageName2邊框.gif";bimg BaseimageName);//獲取背fimg Base(),imageName2);//獲取前imageTracker=new //創(chuàng)建一 // 加入到MedialTracker的監(jiān)視隊列中去,image為要被監(jiān)視的圖像對象, 0width //設(shè)置applet寬height //設(shè)置applet高try //加}catch(InterruptedExceptione)}offI=createImage(width,height);offG=offI.getGraphics();virtualI=createImage(width*2,height*2);virtualG=virtualI.getGraphics();}publicvoidstart(){ //啟動applet,創(chuàng)建并啟動一個線程if(thread==null){threadnew //以applet //啟動線程,調(diào)用run()方}}publicvoidrun(){intx=0,y=0;inttileWidth //設(shè)置招牌寬inttileHeight //設(shè)置招牌高while(thread!=null){try{x=virtualI.getWidth(this)-width;y=virtualI.getHeight(this)-height;forx0&&y0xy //在不同的坐標(biāo)位置輸出圖像以產(chǎn)生邊框效if((x==0)||(y==0))x=virtualI.getWidth(this)-width;y=virtualI.getHeight(this)-height;}forintj0jvirtualI.getHeight(thisjj//輸出圖像,產(chǎn)生邊框特+for(inti=0;i<virtualI.getWidth(this);i=+tileWidth)virtualG.drawImage(bimg,i,j,this);virtualG.drawImage(fimg,virtualG.drawImage(fimg,x,y,width,height,this);offG.drawImage(virtualI,-x,-y,this); //輸出applet,調(diào)用update()}}catch(InterruptedExceptione)}}}publicvoidupdate(Graphicsg){}publicvoidpaint(Graphicsg){g.drawImage(offI,0,0,this);}//調(diào)用paint()//輸出}【代碼解析drawImage(Imageimg,intx,inty,ImageObserverobs)imgdrawImage(Imageimg,intx,inty,intwidth,intheight,ImageObserverobs)img縮表示圖像對象的縮放大小,obsAppletobs的值應(yīng)為實(shí)例 【實(shí)例描述在自己的空間或者博客中經(jīng)常會設(shè)置一些個性相冊來供者瀏覽,以此來提高頁面的量。可以應(yīng)用JavaApplet小程序來實(shí)現(xiàn)這能,具體的運(yùn)行效果如圖14.20所示。14.20【實(shí)現(xiàn)過程EclipsePhotoAlbumPhotoAlbum.java文件。在該類的主方法中publicpublicclassPhotoAlbumextendsApplet{privateChoicemyChoice;privateString[]myString1,myString2;privateinttotalPics;privateImageoffI;privateImage[]img;privateGraphicsoffG;privateMediaTrackerimagetracker;publicvoidinit(){this.setSize(600,450);myChoice=newChoice();myChoice.setBounds(10,10,290,totalPics=myString1=newString[totalPics];myString2=newString[totalPics];img=newImage[totalPics];for(inti=0;i<totalPics;i++){myString1[i]=newString("");myString2[i]=new}Strings=newimagetracker=newfor(inti=0;i<totalPics;i++)String類型的數(shù)組一個int型變量Image對象一組Image對象數(shù)組一個Graphics對象一個MediaTracker對//對Applet//加s="第"+(i+1)+" myString1[i]=s; //向下拉列表中增加選s=(i+1)+".jpg";myString2[i]=s;img[i]=getImage(get Base(),s);imagetracker.addImage(img[i],0);}try}catch(InterruptedExceptione)}offIcreateImage(getSize().widthgetSize().height40);//創(chuàng)建圖offG=offI.getGraphics();offI=img[0];offG.drawImage(offI,0,0,}publicvoidpaint(Graphicsg){g.drawImage(offI,10,40,this);}//使用action()方法來獲得JavaAppletpublicbooleanaction(Evente,Objecto){if(e. ==myChoice){//Strings=newString("");offG.fillRect(0,40,getSize().width,getSize().height-40);offI=img[myChoice.getSelectedIndex()];offG.drawImage(offI,0,0,this);}return}}【代碼解析publicpublicvoidpaint(Graphicsg)g.drawImage(offI,10,40,}通過action()JavaAppletpublicbooleanact

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論