外文翻译-开发Swing应用_第1页
外文翻译-开发Swing应用_第2页
外文翻译-开发Swing应用_第3页
外文翻译-开发Swing应用_第4页
外文翻译-开发Swing应用_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

0外文原文DevelopingSwingApplicationsThefirstexposureofmanypeopletotheJavaprogramminglanguageisintheformofapplets,smallandsecureJavaprogramsthatrunaspartofawebpage.JavaWebStart,aprotocolfordownloadingandrunningJavaprograms,makesitpossibletorunapplicationsfromawebbrowserasiftheywereapplets.Today,youlearnhowtocreatetheseweb-launchedJavaprogramsasyouexplorethefollowingtopics:1.HowtoinstallandrunJavaapplicationsinawebbrowser2.Howtopublishyourapplicationsfilesandrunit3.HowSwingapplicationscanrunintoperformanceslowdownsontime-consumingtasks4.HowtosolvethisproblembyusingSwingWorker,aclassthatper-formsSwingworkinitsownthreadJavaWebStartOneoftheissuesyoumustdealwithasaJavaprogrammerishowtomakeyoursoft-wareavailabletoyourusers.JavaapplicationsrequireaJavainterpreter,soonemusteitherbeincludedwiththeappli-cationorpreviouslyinstalledonthecomputer.Lackingeitherofthose,usersmustinstallaninterpreterthemselves.Theeasiestsolution(foryou)istorequirethatusersdownloadandinstalltheJavaRuntimeEnvironmentfromSunswebsiteat.Regardlessofhowyoudealwiththerequirementforaninterpreter,youdistributeanapplicationlikeanyotherprogram,makingitavailableonaCD,website,orsomeothermeans.Ausermustrunaninstallationprogramtosetitup,ifoneisavailable,orcopythefilesandfoldersmanually.Javaappletsareeasiertomakeavailablebecausetheycanberunbywebbrowsers.However,ifyourprogramisaJavaapplet,usersmustberunningbrowsersequippedwiththeJavaPlug-in.ThistoocanbedownloadedfromSunaspartoftheJavaRuntimeEnvironment.Thereareseveraldrawbackstoofferingappletsinsteadofapplications.Thebiggestisthedefaultsecuritypolicyforapplets,whichmakesitimpossibleforthemtoreadandwritedataonauserscomputer,amongotherrestrictions.1JavaeasesthechallengesofsoftwaredeploymentwithJavaWebStart,ameansofrun-ningJavaapplicationspresentedonawebpageandstoredonawebserver.Hereshowitworks:1.AprogrammerpackagesanapplicationandallthefilesitneedsintoaJARarchivealongwithafilethatusestheJavaNetworkLaunchingProtocol(JNLP),partofJavaWebStart.2.Thefileisstoredonawebserverwithawebpagethatlinkstothatfile.3.Auserloadsthepagewithabrowserandclicksthelink.4.IftheuserdoesnothavetheJavaRuntimeEnvironment,adialogboxopensaskingwhetheritshouldbedownloadedandinstalled.Thefullinstallationismorethan65Minsizeandcouldtake3045minutestodownloadona56KInternetconnection(or35minutesonahigh-speedconnection).5.TheJavaRuntimeEnvironmentinstallsandrunstheprogram,openingnewframesandotherinterfacecomponentslikeanyotherapplication.Theprogramissavedinacache,soitcanberunagainlaterwithoutrequiringinstallation.Toseeitinaction,visitSunsJavaWebStartsiteat/products/javawebstartandclicktheCodeSamples&Appslink,andthenthe“Demos”link.TheWebStartDemospagecontainspicturesofseveralJavaapplications,eachwithaLaunchbuttonyoucanusetoruntheapplication,asshowninFigure14.1.PresentingWebStartapplicationsonawebpage.ClicktheLaunchbuttonofoneoftheapplications.IfyoudonthavetheJavaRuntimeEnvironmentyet,adialogboxopensaskingwhetheryouwanttodownloadandinstallit.TheruntimeenvironmentincludestheJavaPlug-in,aJavainterpreterthataddssupportforthecurrentversionofthelanguagetobrowserssuchasMicrosoftInternetExplorerandMozilla.Theenvironmentalsocanbeusedtorunapplications,regardlessofwhethertheyuseJavaWebStart.WhenanapplicationisrunusingJavaWebStart,atitlescreendisplaysonyourcom-puterbriefly,andtheapplicationsgraphicaluserinterfaceappears.IfyouhaveinstalledtheJDK,youarelikelytohavetheJavaNOTE:RuntimeEnvironmentonyourcomputeralready.Figure14.2showsoneofthedemoapplicationsofferedbySun,amilitarystrategygameinwhichthreeblackdotsattempttokeepareddotfrommovingintotheirterritory.Iftheuserdoesnotpermitsomething,theapplicationcannotfunctionfully.The2kindsofthingsthattriggerasecuritydialogboxarethesamethingsnotallowedbydefaultinapplets:readingandwritingfiles,loadingnetworkresourcesfromserversotherthantheonehostingtheprogram,andthelike.AfteranapplicationhasbeenrunbyJavaWebStart,itisstoredonauserscomputerinacache,enablingittoberunagainlaterwithoutinstallation.Theonlyexceptioniswhenanewversionoftheapplicationbecomesavailable.Inthiscase,thenewversionisdownloadedandinstalledautomaticallyinplaceoftheexistingone.AJavaWebStartapplicationviewercanberundirectlytoseetheapplicationsthathavebeencached,runthem,andchangesomeoftheirsettings.Theapplicationiscalledjavaws.exeandcanbefoundinthesamefolderasjavaandtheothercommand-lineprogramsintheJDK.TherealsoshouldbeamenuitemforJavaWebStartthatwasaddedduringinstallation.AlthoughyourunaJavaWebStartapplicationforthefirsttimeNOTEusingawebbrowser,thatsnotarequirement.Toseethis,runtheJavaWebStartapplicationviewer,selectaprogram,andchooseApplication,InstallShortcuts.Ashortcuttoruntheapplicationwillbeaddedtoyourdesktop.Youcanuseittoruntheprogramwith-outabrowser.ThedefaultsecurityrestrictionsinplaceforaJavaWebStartapplicationcanbeoverrid-denifitisstoredinadigitallysignedJavaarchive.Theuserwillbepresentedwiththesignedsecuritycertificate,whichdocumentstheauthoroftheprogramandthecertificategrantingauthorityvouchingforitsidentity,andaskedwhethertoacceptitorrejectit.Theapplicationwontrununlessthecertificatehasbeenaccepted.UsingJavaWebStartAnyJavaapplicationcanberunusingJavaWebStartaslongasthewebserverthatofferstheapplicationisconfiguredtoworkwiththetechnologyandalltheclassfilesandotherfilesitneedshavebeenpackagedtogether.ToprepareanapplicationtouseJavaWebStart,youmustsavetheapplicationsfilesinaJavaarchivefile,createaspecialJavaWebStartconfigurationfilefortheapplication,anduploadthefilestothewebserver.TheconfigurationfilethatmustbecreatedusesJavaNetworkLaunchingProtocol(JNLP),anExtensibleMarkupLanguage(XML)fileformatthatspecifiestheapplica-tionsmainclassfile,itsJARarchive,andotherthingsabouttheprogram.XMLisintroducedduringDay20,“XMLWebServices.”NOTE:theformatofJNLPfilesisrelativelyself-explanatory,youdontneedtoknowmuchaboutXMLtocreateaJNLPfile.ThenextprojectyouwillundertakeistouseJavaWebStarttolaunchandrunPageData,3anapplicationthatdisplaysinformationaboutwebpages.TheapplicationrequiresthePageData.classfile,whichcanbedownloadedfromtheDay14pageofthebookswebsiteat.(YoualsomightwantPageData.javaincaseyoudecidetomakeanychangestotheapplication.)Togetready,putacopyofthatprojectsclassfileinthefolderyouareusingasawork-spaceforyourJavaprogramming.CreatingaJNLPFileThefirstthingyoumustdoispackageallofanapplicationsclassfilesintoaJavaarchivefilealongwithanyotherfilesitneeds.IfyouareusingtheJDK,youcancreatetheJARfilewiththefollowingcommand:jar-cfPageData.jarPageData.classAJARfilecalledPageData.jariscreatedthatholdstheclassfile.Next,youshouldcreateanicongraphicfortheapplication,whichwillbedisplayedwhenitisloadedandusedasitsiconinmenusanddesktops.TheiconcanbeineitherGIForJPEGformatandshouldbe64pixelswideby64pixelstall.Forthisproject,ifyoudontwanttocreateanewicon,youcandownloadpagedataicon.giffromthebookswebsite.GotoandopetheDay14page.Right-clickthepagedataicon.giflinkandsavethefiletothesamefolderasyourPageData.jarfile.ThefinalthingyoumustdoiscreatetheJNLPfilethatdescribestheapplication.Listin14.1containsaJNLPfileusedtodistributethePageDataapplication.Openyourwordprocessorandenterthetextofthislisting;thensavethefileasPageData.jnlp.ThestructureofaJNLPfileissimilartotheHypertextMarkupLanguage(HTML)requiredtoputaJavaappletonawebpage.Everythingwithinthemarksisatag,andtagsareplacedaroundtheinformationthetagdescribes.Theresanopeningtagbeforetheinformationandaclosingtagafterit.Forexample,line7ofListing14.1containsthefollowingtext:PageDataApplicationInorderfromlefttoright,thislinecontainstheopeningtag,thetextPageDataApplication,andtheclosingtag.Thetextbetweenthetags,“PageDataApplication,”isthetitleoftheapplication.ThistitlewillbedisplayedbyJavaWebStartastheapplicationisbeingloadedandusedinmenusandshortcuts.Thedifferencebetweenopeningtagsandclosingtagsisthatclosingtagsbeginwithaslash(/)character,andopeningtagsdonot.Inline8,istheopeningtag,istheclosingtag,andthesetagssurroundthenameofthevendorwhocre-atedtheapplication.Iveusedmynamehere.Deleteitandreplaceitwithyourown14name,takingcarenottoaltertheortagsaroundit.Sometagshaveanopeningtagonly,suchasline11:4Theoffline-allowedtagindicatesthattheapplicationcanberuneveniftheuserisnotconnectedtotheInternet.IfitwasomittedfromtheJNLPfile,theoppositewouldbetrue,andtheuserwouldbeforcedtogoonlinebeforerunningthisapplication.InXML,alltagsthatdonothaveaclosingtagendwith/insteadof.Tagsalsocanhaveattributes,whichareanotherwaytodefineinformationinanXMLfile.Anattributeisanameinsideatagthatisfollowedbyanequalsignandsometextwithinquotes.Forexample,considerline9ofListing14.1:Thisisthehomepagetag,andithasoneattribute,href.Thetextbetweenthequotemarksisusedtosetthevalueofthisattributeto.Thisdefinesthehomepageoftheapplicationthewebpagethatusersshouldvisitiftheywanttoreadmoreinformationabouttheprogramandhowitworks.ThePageDataJNLPfiledefinesasimpleJavaWebStartapplicationthatrunswithnosecurityrestrictions,asdefinedinlines1719:Inadditiontothetagsthathavealreadybeendescribed,Listing14.1definesotherinfor-mationrequiredbyJavaWebStart.Line1designatesthatthefileusesXMLandtheUTF-8characterset.ThissamelinecanbeusedonanyoftheJNLPfilesyoucreateforapplications.Line2isacomment.LikeothercommentsinJava,itsplacedinthefilesolelyforthebenefitofhumans.JavaWebStartignoresit.Thejnlpelement,whichbeginsonline3andendsonline21,mustsurroundalltheothertagsthatconfigureWebStart.Thistaghastwoattributes,codebaseandhref,whichindicatewheretheJNLPfileforthisapplicationcanbefound.Thecodebaseattributeistheuniformresourcelocator(URL)ofthefolderthatcontainstheJNLPfile.ThehrefattributeisthenameofthefileorarelativeURLthatincludesafolderandthename(suchas“pub/PageData.jnlp”).AccessingDatabaseswithJDBCAlmostallJavaprogramsdealwithdatainsomeway.Youhaveusedprimitivetypes,objects,arrays,linkedlists,andotherdatastructuresuptothispoint.TodayyouworkwithdatainamoresophisticatedwaybyexploringJavaDatabaseConnectivity5(JDBC),aclasslibrarythatconnectsJavapro-gramstorelationaldatabases.Java6includesJavaDB,asmallrelationaldatabasethatspartoftheJavaDevelopmentKit,makingiteasierthanevertoincorporateadata-baseintoyourapplications.TodayyouexploreJDBCandExtensibleMarkupLanguage(XML)inthefol-lowingways:1.UsingJDBCdriverstoworkwithdifferentrelationaldatabases2.AccessingadatabasewithStructuredQueryLanguage(SQL)3.ReadingrecordsfromadatabaseusingSQLandJDBC4.AddingrecordstoadatabaseusingSQLandJDBC5.CreatinganewJavaDBdatabaseandreadingitsrecordsJavaDatabaseConnectivityJavaDatabaseConnectivity(JDBC)isasetofclassesthatcanbeusedtodevelopclient/serverapplicationsthatworkwithdatabasesdevelopedbyMicrosoft,Sybase,Oracle,Informix,andothersources.WithJDBC,youcanusethesamemethodsandclassesinJavaprogramstoreadandwriterecordsandperformotherkindsofdatabaseaccess.Aclasscalledadriveractsasabridgetothedatabasesourcetherearedriversforeachofthepopulardatabases.Client/serversoftwareconnectsauserofinformationwithaproviderofthatinformation,anditsoneofthemostcommonplaceformsofprogramming.YouuseiteverytimeyousurftheWeb:Awebbrowserclientrequestspages,imagefiles,andotherdocumentsusingauniformresourcelocator,orURL.Webserversprovidetherequestedinforma-tion,ifitcanbefound,fortheclient.Oneofthebiggestobstaclesfacedbydatabaseprogrammersisthewidevarietyofdata-baseformatsinuse,eachwithitsownproprietarymethodofaccessingdata.Tosimplifyusingrelationaldatabaseprograms,astandardlanguagecalledSQL(StructuredQueryLanguage)hasbeenintroduced.Thislanguagesupplantstheneedtolearndifferentdatabase-queryinglanguagesforeachdatabaseformat.JavaDB,thedata-baseincludedinJava6,supportsSQL.Indatabaseprogramming,arequestforrecordsinadatabaseiscalledaquery.UsingSQL,youcansendcomplexqueriestoadatabaseandgettherecordsyourelookingforinanyorderyouspecify.Considertheexampleofadatabaseprogrammeratastudentloancompanywhohasbeenaskedtoprepareareportonthemostdelinquentloanrecipients.TheprogrammercoulduseSQLtoqueryadatabaseforallrecordsinwhichthelastpaymentwasmorethan180daysagoandtheamountdueismorethan$0.00.SQLalsocanbeusedtocontrolthe6orderinwhichrecordsarereturned,sotheprogrammercangettherecordsintheorderofSocialSecuritynumber,recipientname,amountowed,oranotherfieldintheloandatabase.AllthisispossiblewithSQLtheprogrammerdoesntneedanyoftheproprietarylan-guagesassociatedwithpopulardatabaseformats.SQListheindustry-standardapproachtoaccessingrelationaldatabases.JDBCsupportsSQL,enablingdeveloperstouseawiderangeofdatabaseformatswithoutknowingthespecificsoftheunderlyingdatabase.JDBCalsosupportstheuseofdatabasequeriesspe-cifictoadatabaseformat.TheJDBCclasslibrarysapproachtoaccessingdatabaseswithSQLiscomparabletoexistingdatabase-developmenttechniques,sointeractingwithanSQLdatabasebyusingJDBCisntmuchdifferentthanusingtraditionaldatabasetools.JavaprogrammerswhoalreadyhavesomedatabaseexperiencecanhitthegroundrunningwithJDBC.TheJDBClibraryincludesclassesforeachofthetaskscommonlyassociatedwithdata-baseusage:1.Makingaconnectiontoadatabase2.CreatingastatementusingSQL3.ExecutingthatSQLqueryinthedatabase4.ViewingtheresultingrecordsTheseJDBCclassesareallpartofthejava.sqlpackage.ConnectingtoanODBCDataSourceYourfirstprojecttodayisaJavaapplicationthatusesaJDBC-ODBCbridgetoconnecttoanAccessfile.TheAccessfileforthisprojectisworld20.mdb,adatabaseofworldenergystatisticspublishedbytheU.S.EnergyInformationAdministration.TheCoaltableinthisdata-baseincludesthreefieldsyouwillbeusingintheproject:1.Country2.Year3.AnthraciteProductionThedatabaseusedinthisprojectisincludedonthisbooksofficialwebsiteat.Tousethisdatabase,youmusthaveanODBCdriveronyoursystemthatsupportsAccessfiles.UsingtheODBCDataSourceAdministrator(orasimilarprogramifyoureonanon-Windowssystem),youmustcreateanewODBCdatasource7associatedwithworld20.mdb.OthersetupworkmightbeneededdependingontheODBCdriverspresentonyoursys-tem,ifany.ConsultthedocumentationincludedwiththeODBCdriver.Afteryouhavedownloadedworld20.mdbtoyourcomputerorfoundanotherdatabasethatscompatiblewiththeODBCdriversonyoursystem,thefinalstepingettingthefilereadyforJDBC-ODBCistocreateadatasourceassociatedwithit.Unlikeotherinput-outputclassesinJava,JDBCdoesntuseafilenametoidentifyadatafileanduseitscontents.Instead,atoolsuchastheODBCDataSourceAdministratorisusedtonametheODBCsourceandindicatethefilefolderwhereitcanbefound.IntheODBCDataSourceAdministrator,clicktheUserDSNtabtoseealistofdatasourcesthatareavailable.Toaddanewoneassociatedwithworld20.mdb(oryourowndatabase),clicktheAddbutton,chooseanODBCdriver,andthenclicktheFinishbutton.ASetupwindowopensthatyoucanusetoprovideaname,shortdescription,andotherinformationaboutthedatabase.ClicktheSelectbuttontofindandchoosethedatabasefile.Figure18.3showstheSetupwindowusedtosetupworld20.mdbasadatasourceintheODBCDataSourceAdministrator.AfteradatabasehasbeenassociatedwithanODBCdatasource,workingwithitinaJavaprogramisrelativelyeasyifyouareconversantwithSQL.ThefirsttaskinaJDBCprogramistoloadthedriver(ordrivers)thatwillbeusedtoconnecttoadatasource.AdriverisloadedwiththeClass.forName(String)method.Class,partofthejava.langpackage,canbeusedtoloadclassesintotheJavainter-preter.TheforName(String)methodloadstheclassnamedbythespecifiedstring.AClassNotFoundExceptioncanbethrownbythismethod.AllprogramsthatuseanODBCdatasourceusesun.jdbc.odbc.JdbcOdbcDriver,theJDBC-ODBCbridgedriverincludedwithJava.LoadingthisclassintoaJavainterpreterrequiresthefollowingstatement:Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);Afterthedriverhasbeenloaded,youcanestablishaconnectiontothedatasourcebyusingtheDriverManagerclassinthejava.sqlpackage.ThegetConnection(String,String,String)methodofDriverManagercanbeusedtosetuptheconnection.ItreturnsareferencetoaConnectionobjectrepresentinganactivedataconnection.Thethreeargumentsofthismethodareasfollows:81.Anameidentifyingthedatasourceandthetypeofdatabaseconnectivityusedtoreachit2.Ausername3.ApasswordThelasttwoitemsareneededonlyifthedatasourceissecuredwithausernameandapassword.Ifnot,theseargumentscanbenullstrings(“”).Thenameofthedatasourceisprecededbythetextjdbc:odbc:whenusingtheJDBC-ODBCbridge,whichindicatesthetypeofdatabaseconnectivityinuse.ThefollowingstatementcouldbeusedtoconnecttoadatasourcecalledPayrollwithausernameof“Doc”andapasswordof“1rover1”:Connectionpayday=DriverManager.getConnection(“jdbc:odbc:Payroll”,“Doc”,“1rover1”);Afteryouhaveaconnection,youcanreuseiteachtimeyouwanttoretrieveorstoreinformationfromthatconnectionsdatasource.ThegetConnection()methodandallotherscalledonadatasourcethrowSQLExceptionerrorsifsomethinggoeswrongasthedatasourceisbeingused.SQLhasitsownerrormessages,andtheyarepassedalongaspartofSQLExceptionobjects.9中文翻译开发Swing应用很多人第一次接触到Java编程语言是小程序,小而安全的Java程序,作为一部分运行的形式网页。JavaWebStart的,一个协议下载和运行Java程序,使得它可以从web浏览器中运行的应用程序,如果他们小程序。今天,您将学习如何创建这些网站推出的Java程序,探讨以下议题:如何安装和在Web浏览器中运行的Java应用程序如何发布您的应用程序的文件并运行它如何Swing应用程序可以在遇到性能下降耗时的任务如何通过使用SwingWorker类,一类解决这个问题的每形式工作摆在它自己的线程JavaWebStart一个你必须处理作为一个Java程序员的问题是如何让你的软洁具提供给用户。Java应用程序需要一个Java解释器,因此必须要么被包含在APPLI阳离子或以前安装在计算机上。缺少其中任何一门,用户必须安装一个解释自己。最简单的解决方案,是要求用户下载。从Sun的网站安装Java运行时环境。不管你如何处理传译员的要求,你分发像任何其他程序,使其成为一个光盘,网站或其他一些可用的应用程序表示。用户必须运行一个安装程序来进行设置,如果有的话,或复制手动的文件和文件夹。Java小程序更容易使用,因为他们可以通过Web浏览器中运行。但是,如果你的程序是一个Java小程序,用户必须运行浏览器的装备与Java插件。这也可以从Sun下载的Java运行时的一部分环境。有几个缺点,以提供小应用程序,而不是应用程序。跌幅最大的是该默认安全策略为小应用程序,这使得他们无法读取和写入用户的计算机,以及其他限制的数据。简化的Java软件部署的挑战使用JavaWebStart,运行的一种手段宁Java应用程序呈现在网页上,并存储在Web服务器上。下面是它的工作原理:1,程序员打包应用程序和所有文件,它需要成为一个JAR归档随着使用Java网络启10动协议(JNLP)文件的一部分,JavaWebStart的。2,该文件存储在Web服务器上有一个网页链接到该文件。3,用户加载页面浏览器,并点击该链接。4,如果用户没有Java运行时环境,将打开一个对话框,询问是否应被下载和安装。完整的安装超过大小65M,可能需要30-45分钟才能下载一个56K互联网连接化(或3-5分钟上高速连接)。5,Java运行时环境安装并运行程序,打开新的框架和其他界面组件,像任何其他应用程序。该程序将保存在一个高速缓存,因此它可以稍后再无需安装即可运行。要看到它在行动,请访问Sun的JavaWebStart的网站/products/JavaWebStart中,然后单击代码示例和应用程序的链接,然后在“演示”链接。该WebStart的演示页面包含多个Java应用程序,每一个启动画面按钮,您可以用它来运行应用程序,启动应用程序在网页上。点击其中一个应用程序的启动按钮。如果您没有Java运行时环境还,将会打开一个对话框,询问您是否要下载并安装它。运行时环境包括Java插件,Java解释,增加了支持对于语言,以浏览器,如MicrosoftInternetExplorer的最新版本和Mozilla。环境还可以用于是否运行的应用程序,而不管他们使用JavaWebStart的。当一个应用程序使用JavaWebStart,一个在你

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论