Vous êtes sur la page 1sur 12

8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform

https://platform.netbeans.org/tutorials/nbm-property-editors.html 1/12
NetBeansIDE
NetBeansPlatform
Plugins
Docs&Support
Community
Partners
Search
netbeans.org>projects>platform>Website
NetBeansPropertyEditorTutorial
ThistutorialshowstechniquesforusingpropertyeditorsinNetBeans,includingprovidingcustomeditorsand
custominplaceeditors.Specifically,thefollowingwillbecovered:
ProvidingyourownpropertyeditorforanindividualNode
Creatingacustomeditor
Creatingacustominplaceeditor
Registeringacustompropertyeditorglobally
Note:ThisdocumentusesNetBeansPlatform8.0andNetBeansIDE8.0.Ifyouareusinganearlier
version,seethepreviousversionofthisdocument.
Contents
IntroductiontoCustomPropertyEditors
CreatingaPropertyEditor
CreatingaCustomEditor
CreatingaCustomInplaceEditor
RegisteringDatePropertyEditorGlobally
UsingPropertyPanel
Tofollowthistutorial,youneedthesoftwareandresourceslistedinthefollowingtable.
SoftwareorResource VersionRequired
NetBeansIDE version8.0orabove
JavaDeveloperKit(JDK) version7orabove
Login|JoinNow|Help
Jump to...
Navigation
Home
MyPage
Projects
People
Project
Features
MailingLists
IssueTracking
Bugzilla
SourceCode
Repository
Platformcontent
Website
Website
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 2/12
Fortroubleshootingpurposes,youarewelcometodownloadthecompletedtutorialsourcecode.
Relatedcommunitytutorials:
CustomFloatPropertyEditor(1)
CustomFloatPropertyEditor(2)
IntroductiontoCustomPropertyEditors
Oftenyoumayhaveapropertyforwhicheitherthestandardpropertyeditorisnotsufficient,ortheproperty
typeisaclassforwhichthereisnostandardpropertyeditor.NetBeansIDEcontainsclassesformanycommon
Javatypes,buteverypossibleneedcannotbecoveredbyasetofgenericpropertyeditors.
Thistutorialisintendedasafollowontotheseprecedingtutorials,anditscodeisbasedonthecodefrom
them:
SelectionManagementTutorialIUsingaTopComponent'sLookup
NetBeansSelectionManagementTutorialIIUsingNodes
UsingtheNodesAPI
You'llpickupwhereyouleftoffintheprevioustutorial,withtheclassEventNode,whichwrapsanEvent
object,andoffersareadonlypropertyforitsindexpropertyandaread/writeoneforitsdateproperty.
CreatingaPropertyEditor
Thebasicsofcreatingapropertyeditorareprettysimple.TheJavaBeansAPIoffersabaseclass,
PropertyEditorSupport,whichcoversmostofthebasics,andcanbeusedtocreateasimplepropertyeditor
withlittlework.
Propertyeditorsservetwopurposesconvertingvaluestoandfromstringsfordisplayinthepropertysheet,
andvalidatingnewvalueswhentheyareset.Tostartout,youwillcreateapropertyeditorwhichsimply
providesandacceptsadifferentlyformatteddate.
1. Rightclicktheorg.myorg.myeditorpackage,andchooseNew>JavaClass.Inthewizard,namethe
classDatePropertyEditor.
2. Inthecodeeditor,changetheclasssignaturetoextendPropertyEditorSupport:
publicclassDatePropertyEditorextendsPropertyEditorSupport{
3. ImplementsetAsText()andgetAsText()asfollows:
@Override
publicStringgetAsText(){
Wiki
NetBeansPlatform
Wiki
WikiHomePage
WikiHomePage
ProjectLinks
Screenshots
Customer
Testimonials
QuickStart
Aboutthis
Project
Platformwas
startedin
November2009,is
ownedbyAntonin
Nebuzelsky,and
has142members.
JoinThisProject
NetBeans.org
Join
News
Releases&
Planning
MailingLists
Bugzilla
Contribute
Teams
Guidelines
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 3/12
Dated=(Date)getValue()
if(d==null){
return"NoDateSet"
}
returnnewSimpleDateFormat("MM/dd/yyHH:mm:ss").format(d)
}
@Override
publicvoidsetAsText(Strings){
try{
setValue(newSimpleDateFormat("MM/dd/yyHH:mm:ss").parse(s))
}catch(ParseExceptionpe){
IllegalArgumentExceptioniae=newIllegalArgumentException("Could
notparsedate")
throwiae
}
}
4. OpenEventNodeinthecodeeditor.ChangethelinethatdeclaresdatePropertysothatthevariable
isdeclaredasPropertySupport.ReflectionratherthanProperty.Youwillbecallingamethod
specifictoPropertySupport.Reflection:
PropertySupport.ReflectiondateProp=newPropertySupport.Reflection(obj,
Date.class,"date")
5. Insertanewlineafterthatline:
dateProp.setPropertyEditorClass(DatePropertyEditor.class)
6. RuntheEventManagerandnotethenewformatoftheDateproperty,asshownhere:
CreatingaCustomEditor
Anotherbasicfeatureofstandardjava.beans.PropertyEditorsistheabilitytohavea"customeditor",
whichusuallyappearsinadialogwhenyouclicka"..."buttonbesidethepropertyinthepropertysheet.
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 4/12
Goingintothedetailsofimplementingsuchaneditorisoutofscopeforthistutorial,butherearethebasics:
1. ImplementthefollowingtwomethodsonDatePropertyEditor:
@Override
publicComponentgetCustomEditor(){
returnnewJLabel("Iwanttobeacustomeditor")
}
@Override
publicbooleansupportsCustomEditor(){
returntrue
}

2. RuntheEventManager,andnowyouhavea"..."buttonbesidethepropertyinthepropertysheet,as
shownbelow:
Clickit,andyourJLabelappears:
Ifyouweredoingthisforreal,youwouldcreateaJPanel,andembedsomesortofcalendarand/or
clockcomponenttomakeiteasytosetthepropertiesthecodenecessarytodoitrightwouldbea
distractionhere.
3. Removebothoftheabovetwomethodsbeforecontinuingbecausewe'regoingtocreatearealdate
editorinthenextsection.
CreatingaCustomInplaceEditor
Whatwouldbereallyusefulistohaveabetterdateeditorembeddedinthepropertysheetitself.NetBeanshas
anAPIthatmakesthispossible.Itinvolvesabitofcode,buttheresultisworthit.
SincetheSwingXprojectincludesanicedatepickercomponent,youwillsimplyreusethat.Sothefirst
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 5/12
thingyouneedtodoistogetSwingXintotheEventManager.SinceNetBeansIDEbundlesSwingX,wewill
usethebundledswingx.jarbybrowsingintotheNetBeansIDEinstallationdirectoryandcreatinganew
modulefromtheswingx.jarthatwewillfindthere.
1. ExpandtheEventManager,rightclicktheModulesnode,andchooseAddNewLibrary,asshownhere:
2. Browseforswingxall1.6.4.jar(orwhateverversionoftheJARisavailable)in"ide/modules/ext"
intheNetBeansIDEinstallationdirectory.
ClickNext.
3. ClickNextagainwithoutmakinganychangestothebelow:
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 6/12
4. Setthecodenamebasetoorg.jdesktop.swingx:
ClickFinishandyoushouldseethenewmodule,wrappingtheselectedJAR:
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 7/12
5. RightclicktheMyEditorprojectnodeintheProjectstabinthemainwindow,andchooseProperties.In
theLibrariespage,clicktheAddDependencybutton,andaddadependencyonyournew"swingxall"
module.WhenyouclickOK,youwillseethenewdependency:
Nowyouarereadytomakeuseofthedatepicker.ThiswillinvolveimplementingacoupleofNetBeansspecific
interfaces:
ExPropertyEditorapropertyeditorinterfacethroughwhichthepropertysheetcanpassan"environment"
(PropertyEnv)objectthatgivestheeditoraccesstothePropertyobjectitiseditingandmore.
InplaceEditor.FactoryaninterfaceforobjectsthatownanInplaceEditor.
InplaceEditoraninterfacethatallowsacustomcomponenttobeprovidedfordisplayintheproperty
sheet.
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 8/12
YouwillimplementInplaceEditor.FactoryandExPropertyEditordirectlyonDatePropertyEditor,
andthencreateanInplaceEditornestedclass:
1. ChangethesignatureofDatePropertyEditorasfollows:
publicclassDatePropertyEditorextendsPropertyEditorSupportimplements
ExPropertyEditor,InplaceEditor.Factory{
2. Asinearlierexamples,pressCtrlShiftItoFixImportsandthenusethe"ImplementAllAbstract
Methods"tocausethemissingmethodstobeadded.
3. AddthefollowingmethodstoDatePropertyEditor:
@Override
publicvoidattachEnv(PropertyEnvenv){
env.registerInplaceEditorFactory(this)
}
privateInplaceEditored=null
@Override
publicInplaceEditorgetInplaceEditor(){
if(ed==null){
ed=newInplace()
}
returned
}
4. NowyouneedtoimplementtheInplaceEditoritself.Thiswillbeanobjectthatownsaswingx
JXDatePickercomponent,andsomeplumbingmethodstosetupitsvalue,anddisposeofresources
whenitisnolongerinuse.Itrequiresabitofcode,butit'sallquitestraightforward.Justcreate
InplaceasastaticnestedclassinsideDatePropertyEditor:
privatestaticclassInplaceimplementsInplaceEditor{
privatefinalJXDatePickerpicker=newJXDatePicker()
privatePropertyEditoreditor=null
@Override
publicvoidconnect(PropertyEditorpropertyEditor,PropertyEnvenv){
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 9/12
editor=propertyEditor
reset()
}
@Override
publicJComponentgetComponent(){
returnpicker
}
@Override
publicvoidclear(){
//avoidmemoryleaks:
editor=null
model=null
}
@Override
publicObjectgetValue(){
returnpicker.getDate()
}
@Override
publicvoidsetValue(Objectobject){
picker.setDate((Date)object)
}
@Override
publicbooleansupportsTextEntry(){
returntrue
}
@Override
publicvoidreset(){
Dated=(Date)editor.getValue()
if(d!=null){
picker.setDate(d)
}
}
@Override
publicKeyStroke[]getKeyStrokes(){
returnnewKeyStroke[0]
}
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 10/12
@Override
publicPropertyEditorgetPropertyEditor(){
returneditor
}
@Override
publicPropertyModelgetPropertyModel(){
returnmodel
}
privatePropertyModelmodel
@Override
publicvoidsetPropertyModel(PropertyModelpropertyModel){
this.model=propertyModel
}
@Override
publicbooleanisKnownComponent(Componentcomponent){
returncomponent==picker||picker.isAncestorOf(component)
}
@Override
publicvoidaddActionListener(ActionListeneractionListener){
//donothingnotneededforthiscomponent
}
@Override
publicvoidremoveActionListener(ActionListeneractionListener){
//donothingnotneededforthiscomponent
}
}
5. Ifyouhaven'talready,pressCtrlShiftItoFixImports.
6. RuntheEventManageragain,selectaninstanceofEventNode,andclickthevalueofthedate
propertyinthepropertysheet.Noticethatthedatepickerpopupappears,andbehavesexactlyasit
should,asshownbelow:
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 11/12
RegisteringDatePropertyEditorGlobally
Oftenitisusefultoregisterapropertyeditortobeusedforallpropertiesofagiventype.Indeed,your
DatePropertyEditorisgenerallyusefulforanypropertyofthetypejava.util.Date.Whileusefulnessis
nottheprimarydeterminantofwhethersuchapropertyeditorshouldberegistered,ifyourapplicationor
modulewillregularlydealwithDateproperties,itmightbeusefultodoso.
HereishowtoregisterDatePropertyEditorsothatanypropertyofthetypejava.util.Datewilluse
DatePropertyEditorinthepropertysheet:
1. AnnotatetheDatePropertyEditorclassasfollows:
@PropertyEditorRegistration(targetType=Date.class)
publicclassDatePropertyEditorextendsPropertyEditorSupportimplements
ExPropertyEditor,InplaceEditor.Factory{
ThiscodewillregisteryourcustomDatePropertyEditorasthedefaulteditorforallproperties
ofthetypejava.util.Datethroughoutthesystem.
2. IntheEventNodeclass,deletethisline,whichisnotneededanymore,thankstothepreviousstep:
dateProp.setPropertyEditorClass(DatePropertyEditor.class)
UsingPropertyPanel
8/29/2014 NetBeans Property Editor API Tutorial for the NetBeans Platform
https://platform.netbeans.org/tutorials/nbm-property-editors.html 12/12
SendUsYourFeedback
Whilewewon'tcoverit,itisworthmentioningthatthepropertysheetisnottheonlyplacethat
Node.PropertyobjectsareusefulthereisalsoaconvenientUIclassinthe
org.openide.explorer.PropertySheetclasscalledPropertyPanel.It'sfunctionistodisplayone
property,muchasitisdisplayedinthepropertysheet,providinganeditorfieldandacustomeditorbutton,or
youhavecalledsomePropertyPanel.setPreferences(PropertyPanel.PREF_CUSTOM_EDITOR),itwill
displaythecustomeditorforaProperty.ItisusefulasaconvenientwaytogetanappropriateUIcomponent
foreditinganygetter/setterpairforwhichthereisapropertyeditor.
SiteMap
AboutUs
Contact
Legal&Licences

Byuseofthiswebsite,youagreetotheNetBeansPoliciesandTermsofUse(revision20140718.4a68f04).2014,OracleCorporation
and/oritsaffiliates.Sponsoredby

Vous aimerez peut-être aussi