仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1706|回复: 19
打印 上一主题 下一主题

[学习教程] JAVA教程之J2ME MIDP Currency Converter Tutoria...

[复制链接]
海妖 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:36:16 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

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这些工具的出来。
愤怒的大鸟 该用户已被删除
沙发
发表于 2015-1-21 10:47:59 | 只看该作者
设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧
再现理想 该用户已被删除
板凳
发表于 2015-1-30 15:54:42 | 只看该作者
是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言
不帅 该用户已被删除
地板
发表于 2015-2-6 13:56:05 | 只看该作者
在全球云计算和移动互联网的产业环境下,Java更具备了显著优势和广阔前景。
老尸 该用户已被删除
5#
发表于 2015-2-16 09:18:48 | 只看该作者
是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言
分手快乐 该用户已被删除
6#
发表于 2015-2-19 17:51:26 | 只看该作者
是一种语言,用以产生「小应用程序(Applet(s))
金色的骷髅 该用户已被删除
7#
发表于 2015-2-28 19:41:28 | 只看该作者
你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?
山那边是海 该用户已被删除
8#
发表于 2015-3-10 07:04:26 | 只看该作者
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
若相依 该用户已被删除
9#
发表于 2015-3-11 10:14:14 | 只看该作者
如果要向java web方向发展也要吧看看《Java web从入门到精通》学完再到《Struts2.0入门到精通》这样你差不多就把代码给学完了。有兴趣可以看一些设计模块和框架的包等等。
飘飘悠悠 该用户已被删除
10#
发表于 2015-3-18 04:22:29 | 只看该作者
是一种语言,用以产生「小应用程序(Applet(s))
深爱那片海 该用户已被删除
11#
发表于 2015-3-21 12:48:41 | 只看该作者
一直感觉JAVA很大,很杂,找不到学习方向,前两天在网上找到了这篇文章,感觉不错,给没有方向的我指了一个方向,先不管对不对,做下来再说。
冷月葬花魂 该用户已被删除
12#
发表于 2015-3-31 05:09:26 | 只看该作者
J2SE开发桌面应用软件比起 VC,VB,DEPHI这些传统开发语言来说,优势好象并不明显。J2ME对于初学者来说,好象又有点深奥,而且一般开发者很难有开发环境。
若天明 该用户已被删除
13#
发表于 2015-4-2 21:24:35 | 只看该作者
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
兰色精灵 该用户已被删除
14#
发表于 2015-4-12 05:38:06 | 只看该作者
一般学编程语言都是从C语开始学的,我也不例外,但还是可能不学过程语言而直接学面向对象语言的,你是刚接触语言,还是从C开始学比较好,基础会很深点,如果你直接学习JAVA也能上手,一般大家在学语言的时候都记一些语言的关键词,常有的包和接口等。再去做逻辑代码的编写,以后的学习过程都是从逻辑代码编写中提升的,所以这方面都是经验积累的。你要开始学习就从
莫相离 该用户已被删除
15#
发表于 2015-4-16 20:10:30 | 只看该作者
象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。
16#
发表于 2015-4-29 16:00:37 | 只看该作者
是一种为 Internet发展的计算机语言
爱飞 该用户已被删除
17#
发表于 2015-5-5 05:49:38 | 只看该作者
是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言
透明 该用户已被删除
18#
发表于 2015-6-17 11:08:17 | 只看该作者
Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站
admin 该用户已被删除
19#
发表于 2015-7-10 06:09:48 | 只看该作者
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
海妖 该用户已被删除
20#
 楼主| 发表于 2015-7-14 12:39:51 | 只看该作者
是一种将安全性(Security)列为第一优先考虑的语言
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-12-29 08:22

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表