JAVA教程之J2ME MIDP Currency Converter Tutoria...
到时我们不用学struts,不用学spring,不用学Hibernate,只要能把jsf学会了,完全可以替代所有的框架,包括AJAX,都知道AJAX并不是新技术,虽说我没深入学习jsf但我认为jsf应该已经能通过其它技术替代AJAX,实现无缝刷新。j2meMIDPCurrencyConverterTutorialforNetBeansIDE4.0Feedbackhttp://www.netbeans.org/kb/articles/tutorial-currencyconverter-40.html
Feedback
TheCurrencyConverterapplicationyouwillbuildinthistutorialshowsyouhowto:
startaj2meMIDPproject
codeaworkingj2meMIDPapplication,orMIDlet,usingtheIDE
createprojectconfigurationstotesttheapplicationsperformanceontwodifferentdeviceemulators
TheCurrencyConverterapplicationconvertsamountsfromonecurrencytotwoothers.Youcanchoosetodisplaythreedifferentcurrencies:euros,yen,ordollars.Youcanalsoenteravalueinonecurrencytobeconvertedintotheotherselectedcurrencies.
TherearethreeJavasourcecodefilesforthesampleapplication:
ConverterMIDlet.java.ThecodefortheMIDletclass.
Converter.java.AMIDPformthatdefinesthemainscreenoftheapplicationasitappearsonamobiledevice.
CurrenciesSelector.java.AMIDPlistthatmaintainsthecurrenciesandrates.
Thefirstpartofthistutorialwillshowyouhowtoquicklyinstall,run,andtesttheCurrencyConverterapplication,whichisavailableasasampleprojectincludedintheIDE.Inthesecondpartofthetutorial,youwillcreateanewprojectandaddcodetocreateandtesttheapplicationyourself.
Thistutorialshouldtakeapproximatelyanhourtocomplete.
Requirements
YoumusthaveNetBeansIDE4.0andtheNetBeansMobilityPack4.0installedbeforeyoucanstartj2meMIDPdevelopment.Seethej2meMIDPDevelopmentDownloadpageforinstructionsondownloadingandinstallingthecompleteenvironment.
InstallingandTestingtheSampleCurrencyConverterProject
Inthisfirstsection,youwillseehowquicklyyoucaninstallandrunasampleprojectontwodifferentemulatordevices.
CreatingtheProjectChooseFile>NewProject.UnderCategories,selectSamples>Mobile.UnderProjects,selectCurrencyConverter.ClickNext.
TheProjectNameandLocationpagesetsthenameandlocationoftheprojectfolder,andgivesyoutheoptionofsettingtheprojectasthemainproject.ClickNexttoacceptthedefaults.
ThePlatformselectionpagesetsthedefaultexecutionenvironment,theemulatorplatform,fortheproject.Notethatthedefaultemulatorplatformisthej2meWirelessToolkit,andthedefaultdeviceistheDefaultColorPhone,agenericmobiledevice.ClickFinishtocompletethewizard.
TheCurrencyConverterdisplaysintheProjectswindow.
RunningtheProjectChooseRun>RunMainProject.
TheCurrencyConverterdisplaysintheDefaultColorPhonedeviceemulator.
Nowyourereadytotesttheapplicationinthedeviceemulator.
TestingtheApplicationIntheDefaultColorPhonescreen,clickthebuttonundertheword"Launch."
Selectthecurrencyyouwanttoconvertbyclickingtheupanddownarrowkeys
ontheSelectbutton.YoucanselectDollars,Euros,orYen.
Enterthecurrencyamounttoconvertbyclickingtheemulator’snumerickeys.
Theapplicationmakestheconversioncalculationsanddisplaystheresults.
Clickthebuttonunderneaththeword“Exit”toexittheapplication.
Clicktheredbuttonintheupperrightcornertoclosetheemulator.
ChangingtheDefaultEmulatorDeviceYoucancreatedifferentprojectconfigurationstotestyourMIDletondifferentemulatorplatforms,orsimplychangethedeviceforthedefaultconfiguration.
ChooseFile>"CurrencyConverter"PropertiesfromtheMainmenu.InthePropertiesdialog,choosethePlatformnode.Youcanchangethedeviceforthedefaultconfiguration.
ClicktheDevicedropdownmenuandchooseQwertyDevice.ClickOK.
ChooseRun>RunMainProjectRuntheapplicationagain,andtheapplicationrunsintheQwertyDeviceemulator.
Inthenextpartofthistutorial,youwillstartover,creatinganewproject.ThiswillgiveyouanopportunitytolearnmoreaboutthecodebehindtheapplicationandhowyoucanusetheIDEtocodeandtestyourownapplications.
CreatingtheCurrencyConverterApplication
CreatingtheProjectChooseFile>NewProject.UnderCategories,selectMobile.UnderProjects,selectMobileApplication.ClickNext.
IntheProjectNameandLocationpage,nametheprojectNewCurrencyConverter,andacceptthedefaultforProjectHome.LeavetheSetasMainProjectcheckboxchecked,asyoullwantthisprojecttobeyourmainprojectClickNext.
AcceptthedefaultsonthePlatformpagebyclickingFinish.
TheNewCurrencyConverterapplicationdisplaysintheProjectswindow.
CreatingtheconverterMIDlet.javaMIDlet
ChooseFile>NewFile.UnderCategories,chooseMIDP.UnderFileTypes,chooseMIDlet.ClickNext.
IntheNameandLocationpage,EnterCurrencyConverterfortheMIDletname,ConverterMIDletfortheMIDPClassName,andmyconverterforthepackagename.
CodingtheMIDlet
YoucanwritethecodeforaMIDletinoneoftwoways:eitherbydirectlyenteringcodeintheSourceEditororbyusingtheIDEtoaddmethods,fields,constructors,initializers,classes,andinterfaces.Typically,youusetheIDEtoaddnewfieldsandmethodstoaclass,ormodifyexistingfieldsandmethods,andthenlaterfine-tunethecodedirectlyintheSourceEditor.
ThefollowingprocedureshowsyouhowtousethetoolandtheSourceEditortoenterorchangecode.However,tosavetimeandeffort,youcanalsocopytheconvertercodefromtheexampleyouinstalled.
CodingtheConverterMIDlet.javaMIDletIntheSourceEditor,addthefollowingimportstatementstoConverterMIDlet.java:
importjava.io.*;importjavax.microedition.rms.*;
IntheProjectsTab,expandtheConverterMIDletnode,right-clicktheConverterMIDletclassandchooseAdd>Field.
ThisnextstepwillusetheAddNewFielddialogboxtoaddthefieldstoredDataStrtotheMIDlet.ThestoredDataStrstringcontainsthenameoftheRMSstoredrecord.
CompletetheAddNewFielddialogbox:
Enterthenameofthenewfield,storedDataStr,intheNameboxandselect
itstype,String,fromtheTypecombobox.
IntheModifiersbox,selectthetypeofaccessforthefield,private,fromthe
Accesscombobox.
Checktheothermodifiersforthefield,whichinthiscaseisstatic.
SettheinitialvalueforstoredDataStrto"ConverterData".
ClickOKtoclosethedialogbox.
ThefieldisaddedtothecodeintheSourceEditorwindow.
AddthefollowingfieldstotheConverterMIDlet.javaclassusingtheSourceEditor.
YoucanusetheAddFielddialogbox,copythetextfromthispage,orfromtheinstalledCurrencyConverterapplication,andpasteitintheSourceEditor.Becareful,however,nottochangethepackagenamefrommyconverter.
publicclassConverterMIDletextendsjavax.microedition.midlet.MIDlet{privatestaticStringstoredDataStr="ConverterData";
publicString[]currencies=newString[]{"US$","Yenu00a5","Eurou20ac"};publicboolean[]selected=newboolean[]{true,true,true,true};publiclong[][]rates={{1000000,117580000,911079},{8504,1000000,7749},
{1097600,129056000,1000000}};privateRecordStorestoredData;
AddthefollowingcodetothemethodstartApp().Thismethodiscalledwhentheapplicationisstarted.Itloadsallthedata(currencies,selectedcurrencies,andexchangerates)frompersistentstorageandinitiallydisplaystheConverterform.Themethodshouldlooklikethis:
publicvoidstartApp(){try{
storedData=RecordStore.openRecordStore(storedDataStr,true);
if(storedData.getNumRecords()>0){
DataInputStreamin=newDataInputStream(newByteArrayInputStream(storedData.getRecord(1)));try{intsize=in.readInt();currencies=newString;selected=newboolean;rates=newlong[];for(inti=0;i<size;i++){currencies=in.readUTF();selected=in.readBoolean();rates=newlong;for(intj=0;j<size;j++){rates=in.readLong();
}}
in.close();}catch(IOExceptionioe){}}}catch(RecordStoreExceptione){}notifySettingsChanged();}
Thedestroyapp()methodiscalledwhentheapplicationisfinished,ordestroyed.AddthefollowingcodetocompletethedestroyApp()method:
publicvoiddestroyApp(booleanunconditional){try{ByteArrayOutputStreambytes=newByteArrayOutputStream();DataOutputStreamout=newDataOutputStream(bytes);try{out.writeInt(currencies.length);for(inti=0;i<currencies.length;i++){out.writeUTF(currencies);out.writeBoolean(selected);for(intj=0;j<currencies.length;j++){out.writeLong(rates);}}out.close();if(storedData.getNumRecords()>0)storedData.setRecord(1,bytes.toByteArray(),0,bytes.size());elsestoredData.addRecord(bytes.toByteArray(),0,bytes.size());}catch(IOExceptionioe){ioe.printStackTrace();}}catch(RecordStoreExceptione){e.printStackTrace();}notifyDestroyed();}
Addthefollowingthreenewmethods:
showSettings()
ThismethodcreatesanddisplaystheCurrenciesSelectorlist.
publicvoidshowSettings(){
Display.getDisplay(this).setCurrent(newCurrenciesSelector(this));
}
notifySettingsChanged()
ThismethoddisplaysanewConverterformafterthesettingsarechanged.
publicvoidnotifySettingsChanged(){Display.getDisplay(this).setCurrent(newConverter(this));}
longconvert()
Thismethodperformsthecurrencyconversion.Theinputvalue,frval,ismultipliedbytheexchangeratestoredintheratestableanddividedby1,000,000.Thefridxandtoidxvaluesaretheindexesofthesourceandtargetcurrencies.
publiclongconvert(longfrval,intfridx,inttoidx){return(frval*rates)/1000000;
8.SavetheConverterMIDletbychoosingFile>Save.
CreatingaMIDPForm
NowthatyouhavecompletedthecodefortheMIDlet,youwillcreatetheapplication’sgraphicalinterface.AformisaJavaclassthatcancontainanarbitrarymixtureofitems,includingimages,read-onlyandeditabletextfields,editabledatefields,gauges,choicegroups,andcustomitems.TheformyoucreateherewillspecifyatextboxforeachselectedcurrencyandspecifytheItemStateListener()methodtomonitorandreflecttypedvaluesandperformconversions.
CodingtheConverter.javaMIDPForm
IntheProjectswindow,right-clickthemyconverterpackage.ChooseFile>NewFile/Folder.
TheNewFilewizardopens.
UnderCategories,expandMIDP,thenexpandMIDPForms.UnderFileTypeschooseMIDPForm.ClickNext.
IntheNameandLocationpage,enterConverterfortheclassname.ClickFinish.
AMIDPformiscreatedandaddedtothemyconverterpackage.
IntheSourceEditor,addthefollowingfieldstothecodebelowthepublicclassConverterdeclaration:
privateConverterMIDletmidlet;privateint[]translate;
Addthefollowingcodetocompletetheconstructor,soitlookslikethesamplebelow:
publicConverter(ConverterMIDletmidlet){super("CurrencyConverter");
this.midlet=midlet;this.translate=newint;intcurrent=0;for(inti=0;i<translate.length;i++){if(midlet.selected){translate=i;append(newTextField(midlet.currencies,"",12,TextField.NUMERIC));}}try{//SetupthisformtolistentocommandeventssetCommandListener(this);//SetupthisformtolistentochangesintheinternalstateofitsinteractiveitemssetItemStateListener(this);//AddtheCurrenciescommandaddCommand(newCommand("Currencies",Command.OK,1));//AddtheExitcommandaddCommand(newCommand("Exit",Command.EXIT,1));
}catch(Exceptione){e.printStackTrace();}
}
AddthefollowingcodetocompletethemethodcommandAction(),soitlookslikethesamplebelow:
publicvoidcommandAction(Commandcommand,Displayabledisplayable){if(command.getCommandType()==Command.EXIT){midlet.destroyApp(true);}elseif(command.getCommandType()==Command.OK){midlet.showSettings();}
}
AddthefollowingcodetocompletetheitemStateChanged()method,soitlookslikethesamplebelow:
publicvoiditemStateChanged(Itemitem){try{longvalue=Long.parseLong(((TextField)item).getString());intfrom=0;while(get(from)!=item)from++;from=translate;for(inti=0;i<size();i++){intto=translate;if(from!=to){((TextField)get(i)).setString(String.valueOf(midlet.convert(value,from,to)));}}}catch(NumberFormatExceptionnfe){for(inti=0;i<size();i++){((TextField)get(i)).setString("");}}}
ThiscompletestheConverter.javaformfile.
CreatingaMIDPList
ThefinalpieceoftheCurrencyConverterapplicationistheCurrenciesSelector.javalistfile,whichdefinesthecurrenciesthatcanbe
selectedfordisplay.
CodingtheCurrenciesSelector.javaMIDPList
IntheProjectswindow,right-clickthemyconverterpackage.ChooseFile>NewFile/Folder.
TheNewFilewizardopens.
UnderCategories,expandMIDP,thenexpandMIDPForms.UnderFileTypeschooseMIDPList.ClickNext.
IntheNameandLocationpage,enterCurrenciesSelectorfortheclassname.ClickFinish.
AMIDPlistfileiscreatedandaddedtothemyconverterpackage.
AfterthelinepublicclassCurrenciesSelectorextendsListimplementsCommandListener{,declareafield:
privateConverterMIDletmidlet;
Addthefollowingcodetocompletetheconstructor,soitlookslikethesamplebelow:
publicCurrenciesSelector(ConverterMIDletmidlet){super("SelectCurrencies",List.MULTIPLE,midlet.currencies,null);this.midlet=midlet;setSelectedFlags(midlet.selected);try{//SetupthislisttolistentocommandeventssetCommandListener(this);//AddtheSavecommandaddCommand(newCommand("Save",Command.OK,1));}catch(Exceptione){e.printStackTrace();}}
AddthefollowingcodetocompletethemethodcommandAction(),soitlookslikethesamplebelow:
publicvoidcommandAction(Commandcommand,Displayabledisplayable){if(command.getCommandType()==Command.OK){getSelectedFlags(midlet.selected);midlet.notifySettingsChanged();}}
ThiscompletestheCurrenciesSelector.javalistfile.
TestingYourApplication
Nowthatyouhavecreatedyourapplication,youcantestitwithdifferentemulatordevices,asyoudidwiththesampleCurrencyConverterprojectyoufirstinstalled.However,insteadofswitchingtheemulatordeviceinthedefaultconfiguration,thistimeyouwillcreateasecondprojectconfigurationfortheQwertyDevicedeviceemulator.
CreatingaNewProjectConfiguration
ChooseFile>"NewCurrencyConverter"Properties.
ClicktheManageConfigurationsbutton.
TheProjectConfigurationManageropens.
ClicktheAddButton.
TheAddConfigurationbuttondisplays.
NamethenewconfigurationQwertyDevice.ClickOk.
ClickClosetoclosetheProjectConfigurationManager.
Younowhaveasecondconfiguration,QwertyDevice,thathasthesamepropertiesastheDefaultConfiguration.
ChangingtheDevicePropertyWhilestillintheProjectProperties,choosePlatformfromthetreemenuintheleftpaneofthewindow.
IfitQwertyDeviceisnotshownastheactiveprojectconfiguration,chooseitfromtheProjectConfigurationdropdownmenu.
Sothatyoucanchoosenewvaluesforthisconfiguration,Uncheckthe"UseValuesfromDefaultConfiguration"checkbox.
ChooseQwertyDevicefromtheDevicedropdownmenu.ClickOK.
RunningtheApplicationonBothConfigurationsMakesurethattheConfigurationdropdownmenuonthetoolbarlistsDefaultConfigurationastheactiveprojectconfiguration.
ChooseRun>RunMainProject.
TheCurrencyConverteropensintheDefaultColorPhoneDeviceemulatorscreen.
ChooseQwertyDevicefromtheConfigurationdropdownmenuinthetoolbar.
ChooseRun>RunMainProject.
TheCurrencyConverteropensintheQwertyDeviceDeviceemulatorscreen.
Nowyoucantestandcomparetheapplicationsperformanceondifferentdevicesatthesametime.
其实你不用Struts,spring这些工具,直接用jsp,servlet能够很方便地写出来,而且,可以根据个人的水平、爱好,有很多方案。而struts,spring这些工具的出来。 设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧 是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言 在全球云计算和移动互联网的产业环境下,Java更具备了显著优势和广阔前景。 是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言 是一种语言,用以产生「小应用程序(Applet(s)) 你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢? Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。 如果要向java web方向发展也要吧看看《Java web从入门到精通》学完再到《Struts2.0入门到精通》这样你差不多就把代码给学完了。有兴趣可以看一些设计模块和框架的包等等。 是一种语言,用以产生「小应用程序(Applet(s)) 一直感觉JAVA很大,很杂,找不到学习方向,前两天在网上找到了这篇文章,感觉不错,给没有方向的我指了一个方向,先不管对不对,做下来再说。 J2SE开发桌面应用软件比起 VC,VB,DEPHI这些传统开发语言来说,优势好象并不明显。J2ME对于初学者来说,好象又有点深奥,而且一般开发者很难有开发环境。 Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。 一般学编程语言都是从C语开始学的,我也不例外,但还是可能不学过程语言而直接学面向对象语言的,你是刚接触语言,还是从C开始学比较好,基础会很深点,如果你直接学习JAVA也能上手,一般大家在学语言的时候都记一些语言的关键词,常有的包和接口等。再去做逻辑代码的编写,以后的学习过程都是从逻辑代码编写中提升的,所以这方面都是经验积累的。你要开始学习就从 象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。 是一种为 Internet发展的计算机语言 是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言 Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站 Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。 是一种将安全性(Security)列为第一优先考虑的语言
页:
[1]