外文翻译6在桌面应用程序中Bean和数据的绑定.docx
《外文翻译6在桌面应用程序中Bean和数据的绑定.docx》由会员分享,可在线阅读,更多相关《外文翻译6在桌面应用程序中Bean和数据的绑定.docx(25页珍藏版)》请在冰豆网上搜索。
外文翻译6在桌面应用程序中Bean和数据的绑定
BindingBeansandDatainaDesktopApplication
ThisguideisanintroductiontothesupportinNetBeansIDE6.0forbeansbindinganddatabindinginJavadesktopapplications.
SoftwareandFilesNeededfortheTutorial
Forthistutorialyouneedtohavethefollowingsoftwareinstalledonyourcomputer:
NetBeansIDE6.0(download).
JavaStandardDevelopmentKit(JDK)version5.0or6.0(download)
Introduction:
BeansBindinginNetBeansIDE6.0
Untilthereleaseofthebeansbindinglibrary,itwassomewhatcumbersometoconnectUIcomponentstodatabasesortokeepvaluesofcomponentpropertiesinsync.Forexample,displayingdatafromastandarddatabaseinaJTablerequiredthemanualcreationofutilityclassestohandletheconnectionbetweenthedatabaseandtheJTable.Andkeepingvaluesofdifferentbeanpropertiesinsync(suchasthevalueofaJTextFieldwiththerenderingofavisualbean)requiredhand-codingoflistenersandeventhandlers.
Thebeansbindinglibrarysimplifiesandstandardizesallofthis.Youcanmerelywriteafewlinesofcodetoestablishwhichpropertiesofwhichcomponentsneedtobekeptinsync,andthebeansbindinglibraryhandlestherest.IntheNetBeansIDE,beansbindingfeaturesareintegratedintheGUIBuilder,soyoucanquicklygetthebehaviorofyourapplicationcodedsoonafteryouhaveestablishedthevisualdesign.
ThisguideisanoverviewofthemainaspectsofbeansbindingintheIDE.Foraconcreteexampleofmanyofthesefeatures,youcantrytheBuildingaJavaDesktopDatabaseApplicationtutorial.
BindingPropertiestoOtherProperties
Atitsmostbasic,beansbindingisawaytoconnectbeanpropertieswithoutusingeventlisteningandhandlingcode.
ToillustratetheconceptofbeansbindingandhowtheIDEsupportsit,wewilldoasimpleexamplewhereausercanadjustaslidertochangeanumericalvalueinatextfield.
Tosetuptheexample:
IntheIDE,choose,File>NewProject.
SelecttheJavacategoryandselecttheJavaApplicationtemplate.ClickNext.
IntheNameandLocationpageofthewizard,performthefollowingoperations:
TypeNumberSliderastheprojectname.
LeavetheSetAsMainProjectcheckboxselected.
CleartheCreateMainClasscheckbox.
ClickFinishtoexitthewizardandsetuptheproject.
IntheProjectswindow,right-clicktheNumberSliderprojectnodeandchooseNew>JFrameForm.
(IfJFrameFormisnotavailableintheNewmenu,chooseOther.ThenintheNewFilewizard,selecttheSwingGUIFormscategoryandselecttheJFrameFormtemplate.)
IntheNameandLocationpageofthewizard,performthefollowingoperations:
TypeNumberSliderFramefortheclassname.
Typenumbersliderforthepackagename.
ClickFinishtoexitthewizardandcreatetheform.
NumberSliderForm.javashouldopenindesignmodeintheeditingarea.
FromtheSwingControlssectionofthePalette,dragaslidercomponentintothedesignarea.(IfthePalettewindowisnotopen,chooseWindow>Palette.)
FromthePalette,dragatextfieldcomponenttothedesignarea.
Theresultingformmightlooksomethinglikethescreenshotbelow.However,positioningisnotimportantforpurposesofthisexample.
SourceandTarget
Nowthatwehavesetuptheexample,wearereadytocreatethebinding.However,firstweneedtodeterminewhichcomponentwillbethesourceofthebindingandwhichwillbethetarget.Thebindingsourcecomponentiswhereavalueforthepropertyfirstoriginates.
WhenbindingintheGUIEditor,youinitiateabindingonthetargetandthenyoudeclarethesourceintheBinddialogbox.
Inthiscase,sincetheJSlidercomeswithadefaultrangeofvalues,wewilluseitasthesource.
Note:
Bindingscanbetwo-way(read/write),sothatchangesinthetargetareautomaticallyreflectedinthesource.However,thedirectionoftheinitialbindingisalwaysfromthesourcetothetarget.SeetheinformationonUpdateModeintheAdvancedBindingConfigurationsection.
Tobindtheslidertothetextfield:
Right-clickthetextfieldcomponentandchooseBind>texttoopentheBinddialogbox.
FromtheBindingSourcecombobox,selectjSlider1.
FromtheBindingExpressioncombobox,selectvalueintasshownintheimagebelow.
ClickOK.
Youhavejustboundthevaluebeanpropertyoftheslidertothetextvalueofthetextfield.
Inthedesignarea,thetextfieldshouldshowthevalue50.Thisvaluereflectsthefactthatthesliderisinthemiddlepositionandthedefaultrangeofvaluesforthesliderisfrom0to100.
Youcannowruntheapplicationandseethebindinginaction.
Toruntheproject:
ChooseRun>RunMainProject.
IntheRunProjectdialogbox,clickOKtoacceptnumberslider.NumberSliderFormasthemainclass.
Theapplicationsshouldstartinaseparatewindow.Adjustthesliderintherunningapplicationandwatchthevaluechangeinthetextfield.
AdvancedBindingConfiguration
Theexampleaboveshowsastraightforwardbindingwithsomedefaultbehaviors.Butsometimesyoumightwantorneedtoconfigureyourbindingdifferently.Ifthatisthecase,youcanusetheAdvancedtaboftheBindingdialogbox.
TheAdvancedtabofthedialogboxcontainsthefollowingfields:
Name.Enablesyoutocreateanameforthebinding,whichgivesyoumoreflexibilityformanagingyourbindings.Thenameisaddedtotheconstructorofthebindingandcanbereferencedwiththebinding'sgetName()method.
UpdateMode.Specifiesthewaythatthepropertiesarekeptsynchronized.Thepossiblevaluesare:
Alwayssync(read/write).Wheneverachangeismadetoeitherthesourceorthetarget,theotherisupdated.
Onlyreadfromsource(readonly).Thetargetisonlyupdatedthefirsttimethesourcevalueisset.Changesthataremadetothesourceareupdatedinthetarget.Changesmadetothetargetarenotupdatedinthesource.
Readfromsourceonce(readonce).Thetargetisonlyupdatedwhenthetargetandsourceareinitiallybound.
UpdateSourceWhen(availableonlytothetextpropertyofJTextFieldandJTextAreacomponents).Enablesyoutoselectthefrequencywithwhichthepropertiesaresynchronized.
IgnoreAdjusting(availabletothevaluepropertyofJSlider;totheselectedElementpropertyofJTableandJList;andtotheselectedElementspropertyofJTableandJList).Ifthischeckboxisselected,anychangesmadetoonepropertyarenotpropagatedtotheotherpropertyuntiltheuserisfinishedmakingthechange.Forexample,whentheapplication'suserdragsaslider,thevalueofthepropertytowhichtheslider'svaluepropertyisboundisonlyupdatedoncetheuserreleasesthemousebutton.
Converter.Ifyourbindinginvolvespropertieswithdifferentdatatypes,youcanspecifycodethatconvertsvaluesbetweenthetypes.Thebeansbindinglibraryhandlesmanycommonlyneededconversions,butyoumightneedtoprovideyourownconvertersforothercombinationsofpropertytypes.Suchconvertersneedtoextendtheorg.jdesktop.beansbinding.Converterclass.
TheConverterdrop-downlistispopulatedwithanyconvertersthathavebeenaddedasbeanstoyourform.Youcanalsoaddtheconversioncodedirectlybyclickingtheellipsis(...)button,andselectingCustomCodefromtheSelectConverterPropertyUsingdrop-downlist.
Validator.Enablesyoutospecifycodetovalidateachangeinthetargetpropertyvaluebeforepropagatingthatchangebacktothesourceproperty.Forexample,youcanuseavalidatortomakesurethatanintegerpropertyvalueiswithinaspecificrange.
Validatorsneedtoextendtheorg.jdesktop.beansbinding.Validatorclass.
TheValidatordrop-downlistispopulatedwithanyvalidatorsthathavebeenaddedasbeanstoyourform.Youcanalsoaddthevalidationcodedirectlybyclickingtheellipsis(...)button,andselectingCustomCodefromtheSelectValidatorPropertyUsingdrop-downlist.
NullSourceValue.Enablesyoutospecifyadifferentvaluetouseifthesourcepropertyhasanullvaluewhenthebindingisattempted.ThisfieldcorrespondswiththesetSourceNullValue()methodoftheorg.jdesktop.beansbinding.Bindingclass.
UnreadableSourceValue.Enablesyoutospecifyadifferentvaluetouseifthebindingexpressioncannotberesolvedwhenthebindingisattempted.ThisfieldcorrespondswiththesetSourceUnreadableValue()methodoftheorg.jdesktop.beansbinding.Bindingclass.
Note:
Tobetterunderstandtheclassesandmethodsmentionedabove,youcanaccessthebeansbindingJavadocdocumentationdirectlyfromtheIDE.ChooseHelp>JavadocReferences>BeansBinding.Inthebrowserwindowthatopens,clicktheorg.jdesktop.beansbindinglinktoaccessdocumentationforthoseclasses.
BindingDatatoComponents
OnceyouhavecreatedanewJavaformandaddedcomponentstotheform,youcangeneratecodetobindthosecomponentstodata.TheIDEmakesiteasytobinddatatoSwingJTable,JList,andJComboBoxcomponents.
Beforebindingacomponenttodatafromadatabase,youneedtohavedonethefollowingthings:
ConnectedtoadatabaseintheIDE.
AddedthecomponenttoaformintheGUIBuilder.
Createdclassesthatrepresentthedatabasetablestowhichyouwanttobind.Stepsoncreatingtheentityclassesforbindingdatatoacomponentaregivenbelow.
CreatingEntityClasses
TocreateentityclassestorepresentthedatabasethatistobeboundtotheJTable:
IntheProjectswindow,right-clickyourprojectandchooseNew>Other,selectthePersistencecategory,andselecttheEntityClassesfromDatabasetemplate.
IntheDatabaseTablespageofthewizard,selectthedatabaseconnection.
OncetheAvailableTablescolumnispopulated,selectthetablesthatyouwanttouseinyourapplication