Sei sulla pagina 1di 7

JavaAppletBasics

Advertisements

PreviousPage NextPage

AnappletisaJavaprogramthatrunsinaWebbrowser.AnappletcanbeafullyfunctionalJavaapplicationbecauseithastheentire
JavaAPIatitsdisposal.

TherearesomeimportantdifferencesbetweenanappletandastandaloneJavaapplication,includingthefollowing

AnappletisaJavaclassthatextendsthejava.applet.Appletclass.

Amain()methodisnotinvokedonanapplet,andanappletclasswillnotdefinemain().

AppletsaredesignedtobeembeddedwithinanHTMLpage.

WhenauserviewsanHTMLpagethatcontainsanapplet,thecodefortheappletisdownloadedtotheuser'smachine.

AJVMisrequiredtoviewanapplet.TheJVMcanbeeitherapluginoftheWebbrowseroraseparateruntimeenvironment.

TheJVMontheuser'smachinecreatesaninstanceoftheappletclassandinvokesvariousmethodsduringtheapplet'slifetime.

AppletshavestrictsecurityrulesthatareenforcedbytheWebbrowser.Thesecurityofanappletisoftenreferredtoassandbox
security,comparingtheapplettoachildplayinginasandboxwithvariousrulesthatmustbefollowed.

OtherclassesthattheappletneedscanbedownloadedinasingleJavaArchive(JAR)file.

LifeCycleofanApplet
FourmethodsintheAppletclassgivesyoutheframeworkonwhichyoubuildanyseriousapplet

initThismethodisintendedforwhateverinitializationisneededforyourapplet.Itiscalledaftertheparamtagsinsidethe
applettaghavebeenprocessed.

startThismethodisautomaticallycalledafterthebrowsercallstheinitmethod.Itisalsocalledwhenevertheuserreturnsto
thepagecontainingtheappletafterhavinggoneofftootherpages.

stopThismethodisautomaticallycalledwhentheusermovesoffthepageonwhichtheappletsits.Itcan,therefore,becalled
repeatedlyinthesameapplet.

destroy This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML
page,youshouldnotnormallyleaveresourcesbehindafterauserleavesthepagethatcontainstheapplet.

paintInvokedimmediatelyafterthestart()method,andalsoanytimetheappletneedstorepaintitselfinthebrowser.The
paint()methodisactuallyinheritedfromthejava.awt.

A"Hello,World"Applet
FollowingisasimpleappletnamedHelloWorldApplet.java

importjava.applet.*;
importjava.awt.*;

publicclassHelloWorldAppletextendsApplet{
publicvoidpaint(Graphicsg){
g.drawString("HelloWorld",25,50);
}
}

Theseimportstatementsbringtheclassesintothescopeofourappletclass

java.applet.Applet

java.awt.Graphics

Withoutthoseimportstatements,theJavacompilerwouldnotrecognizetheclassesAppletandGraphics,whichtheappletclassrefers
to.
TheAppletClass
Everyappletisanextensionofthejava.applet.Appletclass.ThebaseAppletclassprovidesmethodsthataderivedAppletclassmaycall
toobtaininformationandservicesfromthebrowsercontext.

Theseincludemethodsthatdothefollowing

Getappletparameters

GetthenetworklocationoftheHTMLfilethatcontainstheapplet

Getthenetworklocationoftheappletclassdirectory

Printastatusmessageinthebrowser

Fetchanimage

Fetchanaudioclip

Playanaudioclip

Resizetheapplet

Additionally,theAppletclassprovidesaninterfacebywhichtheviewerorbrowserobtainsinformationabouttheappletandcontrolsthe
applet'sexecution.Theviewermay

Requestinformationabouttheauthor,version,andcopyrightoftheapplet

Requestadescriptionoftheparameterstheappletrecognizes

Initializetheapplet

Destroytheapplet

Starttheapplet'sexecution

Stoptheapplet'sexecution

TheAppletclassprovidesdefaultimplementationsofeachofthesemethods.Thoseimplementationsmaybeoverriddenasnecessary.

The"Hello,World"appletiscompleteasitstands.Theonlymethodoverriddenisthepaintmethod.

InvokinganApplet
AnappletmaybeinvokedbyembeddingdirectivesinanHTMLfileandviewingthefilethroughanappletviewerorJavaenabledbrowser.

The<applet>tagisthebasisforembeddinganappletinanHTMLfile.Followingisanexamplethatinvokesthe"Hello,World"applet

<html>
<title>TheHello,WorldApplet</title>
<hr>
<appletcode="HelloWorldApplet.class"width="320"height="120">
IfyourbrowserwasJavaenabled,a"Hello,World"
messagewouldappearhere.
</applet>
<hr>
</html>

NoteYoucanrefertoHTMLAppletTag tounderstandmoreaboutcallingappletfromHTML.

Thecodeattributeofthe<applet>tagisrequired.ItspecifiestheAppletclasstorun.Widthandheightarealsorequiredtospecifythe
initialsizeofthepanelinwhichanappletruns.Theappletdirectivemustbeclosedwithan</applet>tag.

Ifanapplettakesparameters,valuesmaybepassedfortheparametersbyadding<param>tagsbetween<applet>and</applet>.The
browserignorestextandothertagsbetweentheapplettags.

NonJavaenabledbrowsersdonotprocess<applet>and</applet>.Therefore,anythingthatappearsbetweenthetags,notrelatedto
theapplet,isvisibleinnonJavaenabledbrowsers.

TheviewerorbrowserlooksforthecompiledJavacodeatthelocationofthedocument.Tospecifyotherwise,usethecodebaseattribute
ofthe<applet>tagasshown

<appletcodebase="https://amrood.com/applets"code="HelloWorldApplet.class"
width="320"height="120">

If an applet resides in a package other than the default, the holding package must be specified in the code attribute using the period
character(.)toseparatepackage/classcomponents.Forexample

<applet="mypackage.subpackage.TestApplet.class"
width="320"height="120">

GettingAppletParameters
Thefollowingexampledemonstrateshowtomakeanappletrespondtosetupparametersspecifiedinthedocument.Thisappletdisplays
acheckerboardpatternofblackandasecondcolor.

Thesecondcolorandthesizeofeachsquaremaybespecifiedasparameterstotheappletwithinthedocument.

CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint() method. However, getting the
valuesandsavingthesettingsonceatthestartoftheapplet,insteadofateveryrefresh,isconvenientandefficient.

Theappletviewerorbrowsercallstheinit()methodofeachappletitruns.Theviewercallsinit()once,immediatelyafterloadingthe
applet.(Applet.init()isimplementedtodonothing.)Overridethedefaultimplementationtoinsertcustominitializationcode.

TheApplet.getParameter()methodfetchesaparametergiventheparameter'sname(thevalueofaparameterisalwaysastring).Ifthe
valueisnumericorothernoncharacterdata,thestringmustbeparsed.

ThefollowingisaskeletonofCheckerApplet.java

importjava.applet.*;
importjava.awt.*;

publicclassCheckerAppletextendsApplet{
intsquareSize=50;//initializedtodefaultsize
publicvoidinit(){}
privatevoidparseSquareSize(Stringparam){}
privateColorparseColor(Stringparam){}
publicvoidpaint(Graphicsg){}
}

HereareCheckerApplet'sinit()andprivateparseSquareSize()methods

publicvoidinit(){
StringsquareSizeParam=getParameter("squareSize");
parseSquareSize(squareSizeParam);

StringcolorParam=getParameter("color");
Colorfg=parseColor(colorParam);

setBackground(Color.black);
setForeground(fg);
}

privatevoidparseSquareSize(Stringparam){
if(param==null)return;
try{
squareSize=Integer.parseInt(param);
}catch(Exceptione){
//Letdefaultvalueremain
}
}

The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library method Integer.parseInt(),
whichparsesastringandreturnsaninteger.Integer.parseInt()throwsanexceptionwheneveritsargumentisinvalid.

Therefore,parseSquareSize()catchesexceptions,ratherthanallowingtheapplettofailonbadinput.

TheappletcallsparseColor()toparsethecolorparameterintoaColorvalue.parseColor()doesaseriesofstringcomparisonstomatch
theparametervaluetothenameofapredefinedcolor.Youneedtoimplementthesemethodstomakethisappletwork.

SpecifyingAppletParameters
ThefollowingisanexampleofanHTMLfilewithaCheckerAppletembeddedinit.TheHTMLfilespecifiesbothparameterstotheapplet
bymeansofthe<param>tag.

<html>
<title>CheckerboardApplet</title>
<hr>
<appletcode="CheckerApplet.class"width="480"height="320">
<paramname="color"value="blue">
<paramname="squaresize"value="30">
</applet>
<hr>
</html>

NoteParameternamesarenotcasesensitive.

ApplicationConversiontoApplets
ItiseasytoconvertagraphicalJavaapplication(thatis,anapplicationthatusestheAWTandthatyoucanstartwiththeJavaprogram
launcher)intoanappletthatyoucanembedinawebpage.

Followingarethespecificstepsforconvertinganapplicationtoanapplet.

MakeanHTMLpagewiththeappropriatetagtoloadtheappletcode.
SupplyasubclassoftheJAppletclass.Makethisclasspublic.Otherwise,theappletcannotbeloaded.

Eliminate the main method in the application. Do not construct a frame window for the application. Your application will be
displayedinsidethebrowser.

Move any initialization code from the frame window constructor to the init method of the applet. You don't need to explicitly
constructtheappletobject.Thebrowserinstantiatesitforyouandcallstheinitmethod.

RemovethecalltosetSizeforapplets,sizingisdonewiththewidthandheightparametersintheHTMLfile.

RemovethecalltosetDefaultCloseOperation.Anappletcannotbecloseditterminateswhenthebrowserexits.

IftheapplicationcallssetTitle,eliminatethecalltothemethod.Appletscannothavetitlebars.(Youcan,ofcourse,titletheweb
pageitself,usingtheHTMLtitletag.)

Don'tcallsetVisible(true).Theappletisdisplayedautomatically.

EventHandling
Applets inherit a group of eventhandling methods from the Container class. The Container class defines several methods, such as
processKeyEventandprocessMouseEvent,forhandlingparticulartypesofevents,andthenonecatchallmethodcalledprocessEvent.

Inordertoreacttoanevent,anappletmustoverridetheappropriateeventspecificmethod.

importjava.awt.event.MouseListener;
importjava.awt.event.MouseEvent;
importjava.applet.Applet;
importjava.awt.Graphics;

publicclassExampleEventHandlingextendsAppletimplementsMouseListener{
StringBufferstrBuffer;

publicvoidinit(){
addMouseListener(this);
strBuffer=newStringBuffer();
addItem("initializingtheapple");
}

publicvoidstart(){
addItem("startingtheapplet");
}

publicvoidstop(){
addItem("stoppingtheapplet");
}

publicvoiddestroy(){
addItem("unloadingtheapplet");
}

voidaddItem(Stringword){
System.out.println(word);
strBuffer.append(word);
repaint();
}

publicvoidpaint(Graphicsg){
//DrawaRectanglearoundtheapplet'sdisplayarea.
g.drawRect(0,0,
getWidth()1,
getHeight()1);

//displaythestringinsidetherectangle.
g.drawString(strBuffer.toString(),10,20);
}

publicvoidmouseEntered(MouseEventevent){
}
publicvoidmouseExited(MouseEventevent){
}
publicvoidmousePressed(MouseEventevent){
}
publicvoidmouseReleased(MouseEventevent){
}
publicvoidmouseClicked(MouseEventevent){
addItem("mouseclicked!");
}
}

Now,letuscallthisappletasfollows

<html>
<title>EventHandling</title>
<hr>
<appletcode="ExampleEventHandling.class"
width="300"height="300">
</applet>
<hr>
</html>

Initially,theappletwilldisplay"initializingtheapplet.Startingtheapplet."Thenonceyouclickinsidetherectangle,"mouseclicked"will
bedisplayedaswell.

DisplayingImages
AnappletcandisplayimagesoftheformatGIF,JPEG,BMP,andothers.Todisplayanimagewithintheapplet,youusethedrawImage()
methodfoundinthejava.awt.Graphicsclass.

Followingisanexampleillustratingallthestepstoshowimages

importjava.applet.*;
importjava.awt.*;
importjava.net.*;

publicclassImageDemoextendsApplet{
privateImageimage;
privateAppletContextcontext;

publicvoidinit(){
context=this.getAppletContext();
StringimageURL=this.getParameter("image");
if(imageURL==null){
imageURL="java.jpg";
}
try{
URLurl=newURL(this.getDocumentBase(),imageURL);
image=context.getImage(url);
}catch(MalformedURLExceptione){
e.printStackTrace();
//Displayinbrowserstatusbar
context.showStatus("Couldnotloadimage!");
}
}

publicvoidpaint(Graphicsg){
context.showStatus("Displayingimage");
g.drawImage(image,0,0,200,84,null);
g.drawString("www.javalicense.com",35,100);
}
}

Now,letuscallthisappletasfollows

<html>
<title>TheImageDemoapplet</title>
<hr>
<appletcode="ImageDemo.class"width="300"height="200">
<paramname="image"value="java.jpg">
</applet>
<hr>
</html>

PlayingAudio
An applet can play an audio file represented by the AudioClip interface in the java.applet package. The AudioClip interface has three
methods,including

publicvoidplay()Playstheaudiocliponetime,fromthebeginning.

publicvoidloop()Causestheaudiocliptoreplaycontinually.

publicvoidstop()Stopsplayingtheaudioclip.

To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class. The getAudioClip() method returns
immediately,whetherornottheURLresolvestoanactualaudiofile.Theaudiofileisnotdownloadeduntilanattemptismadetoplay
theaudioclip.

Followingisanexampleillustratingallthestepstoplayanaudio

importjava.applet.*;
importjava.awt.*;
importjava.net.*;

publicclassAudioDemoextendsApplet{
privateAudioClipclip;
privateAppletContextcontext;

publicvoidinit(){
context=this.getAppletContext();
StringaudioURL=this.getParameter("audio");
if(audioURL==null){
audioURL="default.au";
}
try{
URLurl=newURL(this.getDocumentBase(),audioURL);
clip=context.getAudioClip(url);
}catch(MalformedURLExceptione){
e.printStackTrace();
context.showStatus("Couldnotloadaudiofile!");
}
}

publicvoidstart(){
if(clip!=null){
clip.loop();
}
}

publicvoidstop(){
if(clip!=null){
clip.stop();
}
}
}

Now,letuscallthisappletasfollows

<html>
<title>TheImageDemoapplet</title>
<hr>
<appletcode="ImageDemo.class"width="0"height="0">
<paramname="audio"value="test.wav">
</applet>
<hr>
</html>

Youcanusetest.wavonyourPCtotesttheaboveexample.

PreviousPage NextPage

Advertisements

Airtel Broadband Plan


Unlimited Free Calls with 100GB
Data @700. Special Offer. Book
Now.

Write for us FAQ's Helping Contact


Copyright 2017. All Rights Reserved.

Enter email for newsletter go

Potrebbero piacerti anche