Tải bản đầy đủ - 0 (trang)
Chapter 23. Scripting Java Applets and Flash Movies

Chapter 23. Scripting Java Applets and Flash Movies

Tải bản đầy đủ - 0trang

suitableforapplicationdevelopmentintheirownright,andboth

canprovidearicheruserexperiencethanDHTML-basedweb

applicationsdo.Onceyourealizehowmuchpowerthesepluginsbringtothewebbrowserenvironment,itisonlynaturalto

wanttotapthatpowerwithJavaScript.Fortunately,youcando

exactlythat.JavaScriptcanbeusedtoscriptbothJavaapplets

andFlashmovies.Furthermoreyoucanevendothereverse:

JavaappletsandFlashmoviescancallJavaScriptfunctions.

Thischapterexplainshowtomakeitwork.Beprepared,

however:theinterfacesbetweenJavaScript,Java,and

ActionScriptareawkward,andifyoudoanyseriousscriptingof

JavaandFlash,youwillencounterincompatibilities,bugs,and

frustration.

Thischapterbeginsbyexplaininghowyoucanuseclient-side

JavaScripttoscriptJavaapplets.(Youmayrememberthat

Example22-14scriptedaJavaapplettocreateclient-side

graphics.)Next,itexplainshow,inFirefoxandrelated

browsers,JavaScriptcodecanscripttheJavaplug-initself,

evenwhennoappletispresent.(Thistechniquewasshownin

Example22-16.)

AfterexplaininghowtoscriptJavawithJavaScript,thischapter

goesontoexplainhowtocreateappletsthatreadandwrite

JavaScriptpropertiesandinvokeJavaScriptmethods,including

appletsthatusetheJavaversionoftheDOMAPItointeract

withthedocumentdisplayedbythewebbrowser.

JavaandJavaScriptarealsocoveredinChapter12.That

chapterwasverydifferent,however.Itdescribedhowtoembed

aJavaScriptinterpreterinaJavaapplicationandhowtoallow

scriptsrunbythatinterpretertointeractwithaJavaprogram.

Chapter12didnotcoverclient-sideJavaScriptnordiditcover

applets.ItdidcoverLiveConnect,atechnologythatenables

JavaScripttocommunicatewithJava,andthematerialon

LiveConnectfromthatchapterisrelevanttothischapter.Note,

however,thatthefeaturesdescribedinChapter12asbeing

specifictothe"RhinoversionofLiveConnect"donotworkwith



client-sideJavaScriptandapplets.

TheJavasectionsofthischapterassumeyouhaveatleasta

basicfamiliaritywithJavaprogramming.Ifyoudonotuse

appletsinyourwebpages,youcanskipthem.

AftercoveringJava,IturntothetopicofscriptingFlash:

allowingJavaScriptcodetoinvokeActionScriptmethodsdefined

withinaFlashmovieandallowingtheActionScriptcodeina

movietocallJavaScriptcode.Idiscussthismaterialtwice,first

coveringtechniquesthatworkinallrecentversionsofFlashand

thencoveringamuchsimplernewtechniquethatworksonlyin

Flashversion8andlater.

BecauseFlashissopowerful,itwasusedinearlierchaptersof

thisbook.InChapter22,theFlashPlayerdisplayeddynamic

client-sidegraphicswiththehelpofsomesimpleActionScript

code(Example22-12)inaFlashmovie.AndinChapter19,

Example19-4tookadvantageoftheFlashPlayer'sclient-side

persistencemechanism.







23.1.ScriptingApplets

Inordertoscriptanapplet,youmustfirstbeabletoreferto

theHTMLelementthatrepresentstheapplet.Asdiscussedin

Chapter15,allJavaappletsembeddedinawebpagebecome

partoftheDocument.applets[]array.Also,ifgivenanameorid,an

appletcanbeaccesseddirectlyasapropertyoftheDocument

object.Forexample,theappletcreatedwithan
name="chart">tagcanbereferredtoasdocument.chart.Andifyou

specifyanidattributeforyourapplet,youcan,ofcourse,look

uptheappletwithDocument.getElementById().

Onceyouhavetheappletobject,thepublicfieldsandmethods

definedbytheappletareaccessibletoJavaScriptasifthey

werethepropertiesandmethodsoftheHTMLelement

itself.Asanexample,considertheCanvasappletdefinedin

Example22-14.Ifaninstanceofthisappletisembeddedinan

HTMLpagewiththeid"canvas",thefollowingcodecanbeused

toinvokemethodsoftheapplet:

varcanvas=document.getElementById('canvas');

canvas.setColor(0x0000ff);

canvas.fillRect(0,0,10,10);

canvas.repaint();



JavaScriptcanqueryandsetthevaluesofpublicfieldsofan

applet,evenfieldsthatarearrays.Supposethatanappletwith

name="chart"definestwofieldsdeclaredasfollows(Javacode):

publicintnumPoints;

publicdouble[]points;



AJavaScriptprogrammightusethesefieldswithcodelikethis:

for(vari=0;i
document.chart.points[i]=i*i;



Thiscodesnippetillustratesthetrickythingaboutconnecting

JavaScriptandJava:typeconversion.Javaisastronglytyped

languagewithanumberofdistinctprimitivetypes;JavaScriptis

looselytypedandhasonlyasinglenumerictype.Inthe

previousexample,aJavaintegerisconvertedtoaJavaScript

number,andvariousJavaScriptnumbersareconvertedtoJava

doublevalues.Thereisalotofworkgoingonbehindthescenes

toensurethatthesevaluesareproperlyconvertedasneeded.

ThetopicofdataconversionwhenJavaScriptisusedtoscript

JavaiscoveredinChapter12,andyoumaywanttoreferback

tothatchapternow.PartIIIalsohasusefulentriesfor

JavaObject,JavaArray,JavaClass,andJavaPackage.Notethat

Chapter12documentsLiveConnect,atechnologythat

originatedwithNetscape.NotallbrowsersuseLiveConnect.IE,

forexample,usesitsownActiveXtechnologyasthebridge

betweenJavaScriptandJava.Regardlessofthetechnology

underneath,thebasicrulesforconvertingvaluesbetweenJava

andJavaScriptaremoreorlessthesameinallbrowsers.

Finally,itisalsoimportanttonotethatJavamethodscanreturn

Javaobjects,andJavaScriptcanreadandwritethepublicfields

andinvokethepublicmethodsofthoseobjectsjustasitcando

withtheappletobject.JavaScriptcanalsouseJavaobjectsas

argumentstoJavamethods.ConsidertheCanvasappletof

Example22-14again.ItdefinesmethodsthatreturnShape

objects.JavaScriptcodecaninvokemethodsoftheseShape

objects,anditcanpassthemtootherappletmethodsthat

expectShapearguments.

Example23-1isasampleJavaappletthatdoesnothingbut



defineausefulmethodforJavaScripttoinvoke.ThisgetText()

methodreadsaURL(whichmustcomefromthesameserver

astheappletdid)andreturnsitscontentasaJavastring.

Here'sanexamplethatusesthisappletinasimpleself-listing

HTMLfile:










Example23-1usesbasicJavanetworking,I/O,andtext

manipulationclasses,butdoesn'tdoanythingparticularlytricky.

Itsimplydefinesausefulmethodanddeclaresitpublicsothat

JavaScriptcanscriptit.



Example23-1.Anappletsuitableforscripting



importjava.applet.Applet;

importjava.net.URL;

importjava.io.*;

publicclassGetTextAppletextendsApplet{

publicStringgetText(Stringurl)

throwsjava.net.MalformedURLException,java.io.IOException

{

URLresource=newURL(this.getDocumentBase(),url);

InputStreamis=resource.openStream();

BufferedReaderin=newBufferedReader(newInputStreamReader(is));

StringBuildertext=newStringBuilder();

Stringline;

while((line=in.readLine())!=null){

text.append(line);

text.append("\n");

}

in.close();

returntext.toString();

}

}







23.2.ScriptingtheJavaPlug-in

Inadditiontoscriptingapplets,Firefoxandrelatedbrowsers

canscripttheJavaplug-indirectlywithouttheneedforan

applet.LiveConnecttechnologyallowsJavaScriptcoderunning

inthesebrowserstoinstantiateJavaobjectsandusethem,

evenintheabsenceofanapplet.Thistechniqueisnotportable,

however,anddoesnotworkinbrowserssuchasInternet

Explorer.

Inbrowsersthatsupportthisplug-inscriptingcapability,the

PackagesobjectprovidesaccesstoallJavapackagesthebrowser

knowsabout.TheexpressionPackages.java.langreferstothe

java.langpackage,andtheexpressionPackages.java.lang.System

referstothejava.lang.Systemclass.Forconvenience,javaisa

shortcutforPackages.java(seethePackagesandjavaentriesin

PartIII).SoJavaScriptcodemightinvokeastaticmethodof

thisjava.lang.Systemclassasfollows:



//InvokethestaticJavamethodSystem.getProperty()

varjavaVersion=java.lang.System.getProperty("java.version");



However,you'renotlimitedtousingstaticmethodsand

predefinedobjects:LiveConnectallowsyoutousethe

JavaScriptnewoperatortocreatenewinstancesofJavaclasses.

Example23-2showsJavaScriptcodethatcreatesanewJava

windowanddisplaysamessageinit.NotethatthisJavaScript

codelooksalmostlikeJavacode.Thiscodefirstappearedin

Chapter12,buthereitisembeddedina



WhenyouscripttheJavaplug-in,yourscriptsaresubjecttothe

samesecurityrestrictionsthatuntrustedappletsare.A

JavaScriptprogramcannotusethejava.io.Fileclass,for

example,becausethatwouldgiveitthepowertoread,write,

anddeletefilesontheclientsystem.







23.3.ScriptingwithJava

HavingexploredhowtocontrolJavafromJavaScriptcode,let's

nowturntotheoppositeproblem:howtocontrolJavaScript

fromaJavaapplet.AllJavainteractionswithJavaScriptare

handledthroughaninstanceofthenetscape.javascript.JSObject

class.(CompletedocumentationforJSObjectisinPartIV.)An

instanceofthisclassisawrapperaroundasingleJavaScript

object.Theclassdefinesmethodsthatallowyoutoreadand

writepropertyvaluesandarrayelementsoftheJavaScript

objectandtoinvokemethodsoftheobject.Hereisasynopsis

ofthisclass:



publicfinalclassJSObjectextendsObject{

//ThisstaticmethodreturnsaninitialJSObjectfortheb

publicstaticJSObjectgetWindow(java.applet.Appletapplet)



//Theseinstancemethodsmanipulatetheobject

publicObjectgetMember(Stringname);//Read

publicObjectgetSlot(intindex);//Read

publicvoidsetMember(Stringname,Objectvalue);//Seto

publicvoidsetSlot(intindex,Objectvalue);//Seta

publicvoidremoveMember(Stringname);//Delet

publicObjectcall(Stringname,Objectargs[]);//Invok

publicObjecteval(Strings);//Evalu

publicStringtoString();//Co

protectedvoidfinalize();

}



TheJSObjectclassdoesnothaveaconstructor.AJavaapplet

obtainsitsfirstJSObjectwiththestaticgetWindow()method.

Whenpassedareferencetoanapplet,thismethodreturnsa

JSObjectthatrepresentsthebrowserwindowinwhichthe



appletappears.Thus,everyappletthatinteractswith

JavaScriptincludesalinethatlookssomethinglikethis:



JSObjectwin=JSObject.getWindow(this);//"this"istheappl



HavingobtainedaJSObjectthatreferstotheWindowobject,

youcanuseinstancemethodsofthisinitialJSObjecttoobtain

otherJSObjectsrepresentingotherJavaScriptobjects:



importnetscape.javascript.JSObject;//Thismustbeattheto

...

//GettheinitialJSObjectrepresentingtheWindow

JSObjectwin=JSObject.getWindow(this);//window

//UsegetMember()togetaJSObjectrepresentingtheDocument

JSObjectdoc=(JSObject)win.getMember("document");//.docume

//Usecall()togetaJSObjectrepresentinganelementofthe

JSObjectdiv=(JSObject)doc.call("getElementById",//.getEle

newObject[]{"test"});



NotethatgetMember()andcall()bothreturnavalueoftype

Object,whichgenerallymustbecasttosomemorespecific

type,suchasJSObject.Alsonotethatwhenyouinvokea

JavaScriptmethodwithcall(),youpassargumentsasanarray

ofJavaObjectvalues.Thisarrayisrequiredevenifthemethod

youareinvokingexpectsoneargumentornoneatall.

TheJSObjectclasshasonemoreimportantmethod:eval().This

JavamethodworksliketheJavaScriptfunctionofthesame

name:itexecutesastringthatcontainsJavaScriptcode.You'll

findthatusingeval()isoftenmucheasierthanusingtheother

methodsoftheJSObjectclass.Forexample,considerthe

followinguseofeval()tosetaCSSstyleonadocument

element:



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 23. Scripting Java Applets and Flash Movies

Tải bản đầy đủ ngay(0 tr)

×