|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
到时我们不用学struts,不用学spring,不用学Hibernate,只要能把jsf学会了,完全可以替代所有的框架,包括AJAX,都知道AJAX并不是新技术,虽说我没深入学习jsf但我认为jsf应该已经能通过其它技术替代AJAX,实现无缝刷新。j2meMIDPCurrencyConverterTutorialforNetBeansIDE4.0
Feedbackhttp://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[size];selected=newboolean[size];rates=newlong[size][];for(inti=0;i<size;i++){currencies[i]=in.readUTF();selected[i]=in.readBoolean();rates[i]=newlong[size];for(intj=0;j<size;j++){rates[i][j]=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[i]);out.writeBoolean(selected[i]);for(intj=0;j<currencies.length;j++){out.writeLong(rates[i][j]);}}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[fridx][toidx])/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[midlet.currencies.length];intcurrent=0;for(inti=0;i<translate.length;i++){if(midlet.selected[i]){translate[current++]=i;append(newTextField(midlet.currencies[i],"",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[from];for(inti=0;i<size();i++){intto=translate[i];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这些工具的出来。 |
|