1.Using Nodes

  • View
    13

  • Download
    5

Embed Size (px)

DESCRIPTION

Netbeans Platform Tutorial (Nodes API)

Text of 1.Using Nodes

  • 8/29/2014 NetBeans Selection Management Tutorial IIUsing Nodes for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-selection-2.html 1/12

    NetBeansIDE

    NetBeansPlatform

    Plugins

    Docs&Support

    Community

    Partners

    Search netbeans.org>projects>platform>Website

    NetBeansSelectionManagementTutorialIIUsingNodesTheprevioustutorialcoveredthebasicsofcomponentwideselectionhandlinginNetBeanshowtoprovideobjectsfromaTopComponent'sLookup,andhowtowriteothercomponentsthataresensitivetotheLookupofwhatevercomponenthasfocus.

    ThistutorialfocusesontheNodesAPI,whichmakesitpossibletodomoregranularviewsandselectionthanjustcomponentlevelselection.Ofcourse,youcouldwriteacomponentthatreadsandwritesintoitsownLookupwhateveritwants,andprovidesmoregranularselectionlogicthatway.ButtheNodesAPImakesitveryeasytodothis,andoffersanumberofadvantagesoverdoingityourself.

    Note:ThisdocumentusesNetBeansPlatform8.0andNetBeansIDE8.0.Ifyouareusinganearlierversion,seethepreviousversionofthisdocument.

    Contents

    IntroductiontotheNodesAPICreatinganExplorerViewImplementingNodesandNodeChildrenRunningtheTutorialExploringExplorerHandlingMultiSelectionReviewofConceptsNextSteps

    Tofollowthistutorial,youneedthesoftwareandresourceslistedinthefollowingtable.

    SoftwareorResource VersionRequired

    Login|JoinNow|Help

    Jump to...

    NavigationHome

    MyPage

    Projects

    People

    ProjectFeatures

    MailingLists

    IssueTracking

    Bugzilla

    SourceCodeRepository

    Platformcontent

    Website

    Website

  • 8/29/2014 NetBeans Selection Management Tutorial IIUsing Nodes for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-selection-2.html 2/12

    NetBeansIDE version8.0oraboveJavaDeveloperKit(JDK) version7orabove

    Fortroubleshootingpurposes,youarewelcometodownloadthecompletedtutorialsourcecode.

    IntroductiontotheNodesAPIThefirstadvantageisthattheNodesAPIprovidesapresentationlayeralayerbetweenthedatamodelbeingeditedinsomeway,andtheUIcomponentsthatexposethedatamodeltotheuser.Thisisquiteusefulandpowerful,asthesamemodelmaybepresentedinmultipleways,orwithmultipleUIs.

    ThesecondadvantageistheExplorerAPIthemoduleorg.openide.explorerprovidesavastarrayofcomponentstrees,lists,treetablesandmorewhichcanrenderaNodeanditschildren.

    ANodeisagenerichierarchicalobjectaNodehas:

    ChildrenNodesinahierarchyunderneathit,thatcanbedisplayedinatree

    ActionsAnarrayofactionsthatcanbedisplayedinapopupmenu

    DisplayNameAhumanreadable,localizeddisplaynamethatcanbeshowninaUIcomponent

    IconAniconthatcanbeshowninaUIcomponent

    andNodescanfirechangesinanyoftheabove,andtheexplorerUIcomponentswillautomaticallyupdatethemselves.

    Thisisnottosaythatthecontentoftheprevioustutorialwasuselessonthecontrary,itisthereasontheNodesAPIcanwork.Thereason:org.openide.nodes.Nodehasamethod,youguessedit,getLookup().InfactwhatishappeningwhenyouchangeselectionintheProjectstabintheIDE,forexample,is...theProjectstabisaTopComponent.ItproxiestheLookupofwhateverobject(s)arecurrentlyselectedinthetreejustastheUtilities.actionsGlobalContext()Lookupproxieswhichevercomponentisfocusedandfireschangeswhenfocuschanges.

    ThankstothecomponentsintheExplorerAPI,itisveryeasytocreateyourownviewsofatreeofNodes,andhavethistypeofproxyinginyourowncomponentswithverylittlecode.ViewertypecomponentssuchastheMyViewercomponentintheprevioustutorialdonothavetodoanythingspecialtobeabletorespondtoselectionchangesinExplorercomponentstheywillautomaticallybenotifiedasselectionchanges.

    CreatinganExplorerViewThefirstthingyouwilldoissomesubstantialmodificationstoyourMyEditoreditorcomponent.Thisstartswithopeningitintheeditor.

    1. First,bringupthepropertiesdialogfortheMyEditorprojectbyrightclickingtheMyEditorprojectandchoosingProperties.OntheLibrariestab,clicktheAddDependencybutton,andtype"BeanTreeView"inthedialog:

    Wiki

    NetBeansPlatformWiki

    WikiHomePage

    WikiHomePage

    ProjectLinksScreenshots

    CustomerTestimonials

    QuickStart

    AboutthisProjectPlatformwasstartedinNovember2009,isownedbyAntoninNebuzelsky,andhas142members.

    JoinThisProject

    NetBeans.orgJoin

    News

    Releases&Planning

    MailingLists

    Bugzilla

    Contribute

    Teams

    Guidelines

  • 8/29/2014 NetBeans Selection Management Tutorial IIUsing Nodes for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-selection-2.html 3/12

    ClickOKonceyouseetheExplorer&PropertySheetAPIlisted,asshownabove.ThiswilladdadependencyontheExplorerAPImodule,soyoucanuseclassesfromit.

    2. Switchtotheformdesigner,selectallofthecomponents,anddeletethem.Inthenextsteps,wewilluseacomponentfromtheExplorer&PropertySheetAPI,insteadofthetextfieldsandbuttonwehavebeenusingsofar.

    3. RewritetheconstructoroftheMyEditorclassasshownbelow:

    publicMyEditor(){

    initComponents()Eventobj=newEvent()associateLookup(newAbstractLookup(content))

    setLayout(newBorderLayout())add(newBeanTreeView(),BorderLayout.CENTER)

    setDisplayName("MyEditor"+obj.getIndex())

  • 8/29/2014 NetBeans Selection Management Tutorial IIUsing Nodes for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-selection-2.html 4/12

    }

    BeanTreeViewisacomponentfromtheExplorer&PropertySheetAPIabasicJTreebasedviewoveraNodeanditschildren,withbuiltinhandlingofpopupmenus,searchingandmore.PressCtrlShiftItoimportBeanTreeView,becausetheimportstatementneedstobeadded.

    4. Thenextstepistogiveyourtreesomethingtoshow.ExplorerUIcomponentsworklikethis:Whenaddedtoacontainer,theysearchthatcontainerandtheirancestorsuntiltheyfindonethatimplementsExplorerManager.Provider.Soyoudon'tsetthenodetobevieweddirectlyonthecomponentyousetitonthecomponent'smanager.Thismakesitpossibletohavemultipleviews,master/detailviewsandsuch,allmanagedbyasinglemanager.AddtothesignatureofMyEditorasfollows:

    publicclassMyEditorextendsTopComponentimplementsExplorerManager.Provider{

    ThenpressCtrlShiftItofiximports.Keepingthecaretinthesignatureline,alightbulbglyphshouldappearinthemargin.PressAltEnter,andacceptthehint"Implementallabstractmethods".Thiswilladdonemethod,getExplorerManager().Implementitasfollows:

    privatefinalExplorerManagermgr=newExplorerManager()

    publicExplorerManagergetExplorerManager(){returnmgr}

    5. Now,sincethegoalisonecomponentthatcandisplaymultipleEvents,youneedaNodeortwotodisplayinyourcomponent.EachonewillownitsowninstanceofEvent.So,rightnowyou'lljustaddthecodethatwillcreatearootnodeforyourtreeview.Addthefollowinglinetotheconstructor:

    mgr.setRootContext(newAbstractNode(Children.create(newEventChildFactory(),true)))

    ThisisthecodethatsetstherootnodeforalloftheexplorerviewsthatarechildcomponentsofMyEditor.TheChildren.createisastaticcallfromtheNetBeansAPIsthatwill,thankstothetrueparameter,createthechildcomponentsasynchronously,thatis,asneeded,insteadofallatonce.

    6. IfyoutriedFixImports,youmayhaveseentheerrordialogtellingyouthatneitherAbstractNode,Children,norEventChildFactorycouldberesolved.ToresolveAbstractNodeandChildren,youneedtoaddonedependency,ontheNodesAPImodule.RightclicktheMyEditorproject,gotothe

  • 8/29/2014 NetBeans Selection Management Tutorial IIUsing Nodes for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-selection-2.html 5/12

    LibrariespageandclickAddDependency.Type"AbstractNode"intheAdddialog,andwhentheitem"NodesAPI"inthelistisselected,clickOKorpressEnter.

    7. Now,backinthesourceeditor,pressCtrlShiftItoFixImports.YouwillbenotifiedthatEventChildFactorycouldnotberesolved.That'sokayyou'reabouttowriteit,inthenextsection.

    ImplementingNodesandNodeChildrenYou'llnoticeyou'reusingaclasscalledAbstractNodeabove.Despiteitsname,itisnotanabstractclass!Itisautilityimplementationoforg.openide.nodes.NodewhichcansaveyousometimeandtroubleratherthanimplementNodeyourself,youcanjustcreateanAbstractNodeandpassitaChildrenobjectwhichwillprovidechildnodesforit,andthensetitsiconanddisplaynameasneeded.SoitisasimplewaytogetaNodeobjecttorepresentsomething,withoutneedingtodoanysubclassingofNodeitself.

    ThenextstepistoimplementEventChildFactory,sothattherearesubnodesunderneaththeinitialnode.

    1. Rightclicktheorg.myorg.myeditorpackageintheMyEditorproject,andchooseNew>JavaClassfromthepopupmenu.IntheNewJavaClasswizard,nametheclass"EventChildFactory",andclickFinishorpressEntertocreatetheclass.

    2. ModifythesignatureoftheclasssoitextendsChildFactory:

    classEventChildFactoryextendsChildFactory{

    PressCtrlShiftItoFixImports.

    3. Positionthecaretintheclasssignatureline.Whenthelightbulbglyphappearsinthemargin,pressAltEnterandthenEnteragaintoacceptthehint"ImplementallAbstractMethods".ThiswilladdacreateKeys(ListtoPopulate)methodthisiswhereyouwillcreatethekeys,onabackgroundthread,thatwillbeusedtocreatethechildrenofyourrootnode.

    4. Butfirst,youwanttooverrideonemethodcreateKeys.ChildrenFactory.createKeysiscalledthefirsttimesomethingpaysattentiontothisChildrenobjectthefirsttimeitisaskedforitschildnodes.SoyoucandelaycreationofchildNodesuntiltheuserhasreallyexpandedtheparentnodeinaviewandneedstoseethem.Implementthemethodasfollows:

    @OverrideprotectedbooleancreateKeys(ListtoPopulate){Event[]objs=newEvent[5]for(inti=0i

  • 8/29/2014 NetBeans Selection Management Tutorial IIUsing Nodes for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-selection-2.html 6/12

    returntrue}

    AsyoumayhaveguessedfromthenameChildFactory,whatyourparentclassdoesistakeanarrayorCollectionofkeyobjects,andactasafactoryforNodesforthem.ForeachelementinthearrayorcollectionyoupasstothetoPopulatelistabove,thecreateNodeForKey()shownbelowwillbecalledoncewhentrueisreturned(notethismeansthatifyouwant,youcanhavemorethanonenodetorepresentoneobject).