3.NetBeans Nodes API Tutorial

Embed Size (px)

Citation preview

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    1/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 1/22

    NetBeans IDE

    NetBeans Platform

    Plugins

    Docs & Support

    Community

    Partners

    Search

    netbeans.org> projects > platform > Website

    NetBeans Nodes API TutorialThis tutorial shows how to make use of some of the features of the Nodes API in NetBeans. It shows how to do

    the following:

    Decorate Nodes with icons

    Use HTML markup to enhance how Nodes are displayed

    Create properties for display in the property sheet

    Provide Actions from Nodes

    This tutorial is intended as a follow-on to the NetBeans Selection Management Tutorial, which covers how

    Lookup is used in managing selection in the NetBeans windowing system, and its follow-on tutorial which

    demonstrates how to use the Nodes API in managing selection.

    As its basis, this tutorial uses the source code created in the first tutorial and enhanced further in the second. If

    you have not yet done these tutorials, it is recommended to do them first.

    Note: This document uses NetBeans Platform 8.0 and NetBeans IDE 8.0. If you are using an earlier

    version, see the previous version of this document.

    Contents

    Creating a Node subclass

    Enhancing Display Names with HTML

    Providing Icons

    Actions and Nodes

    PresentersProperties and the Property Sheet

    Login | Join Now | Help

    Jump to...

    NavigationHome

    My Page

    Projects

    People

    Project

    FeaturesMailing Lists

    Issue Tracking

    Bugzilla

    Source Code

    Repository

    Platform content

    Website

    Website

    http://-/?-http://-/?-http://-/?-https://netbeans.org/mypagehttps://netbeans.org/https://netbeans.org/projectshttps://netbeans.org/projects/platformhttps://netbeans.org/projects/platform/contenthttp://plugins.netbeans.org/PluginPortal/https://netbeans.org/features/platform/index.htmlhttps://netbeans.org/https://netbeans.org/https://netbeans.org/https://netbeans.org/http://platform.netbeans.org/https://netbeans.org/projects/platform/sources/platform-content/showhttps://netbeans.org/projects/platform/sourceshttp://netbeans.org/bugzilla/buglist.cgi?product=platform&order=Importance&limit=25https://netbeans.org/projects/platform/listshttps://netbeans.org/peoplehttps://netbeans.org/projectshttps://netbeans.org/mypagehttps://netbeans.org/https://netbeans.org/projects/help/pages/WebSite#WithNavigationhttps://netbeans.org/people/newhttps://netbeans.org/people/login?original_uri=https%3A%2F%2Fplatform.netbeans.org%2Ftutorials%2Fnbm-nodesapi2.htmlhttp://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-https://platform.netbeans.org/tutorials/74/nbm-nodesapi2.htmlhttps://platform.netbeans.org/tutorials/nbm-selection-2.htmlhttps://platform.netbeans.org/tutorials/nbm-selection-1.htmlhttps://netbeans.org/projects/platform/contenthttps://netbeans.org/projects/platformhttps://netbeans.org/projectshttps://netbeans.org/https://netbeans.org/community/partners/index.htmlhttps://netbeans.org/community/index.htmlhttps://netbeans.org/kb/index.htmlhttp://plugins.netbeans.org/PluginPortal/https://netbeans.org/features/platform/index.htmlhttps://netbeans.org/features/index.htmlhttps://netbeans.org/
  • 8/10/2019 3.NetBeans Nodes API Tutorial

    2/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 2/22

    Read-Write Properties

    Grouping Property Sets

    General Property Sheet Caveats

    Review of Concepts

    Next Steps

    To follow this tutorial, you need the software and resources listed in the following table.

    Software or Resource Version Required

    NetBeans IDE version 8.0 or above

    Java Developer Kit (JDK) version 7 or above

    For troubleshooting purposes, you are welcome to download the completed tutorial source code.

    Creating a Node subclass

    As mentioned in the previous tutorial, Nodes arepresentation objects. That means that they are not a data

    model themselvesrather, they are a presentation layer for an underlying data model. In the Projects or Files

    windows in the NetBeans IDE, you can see Nodes used in a case where the underlying data model is files on

    disk. In the Services window in the IDE, you can see them used in a case where the underlying objects are

    configurable aspects of NetBeans runtime environment, such as available application servers and databases.

    As a presentation layer, Nodes add human-friendly attributes to the objects they model. The essential ones are:

    Display Namea human readable, user-friendly display name

    Descriptiona human readable, user-friendly description, often shown as a tooltip

    Iconsome glyph that graphically indicates the type of object shown and possibly its state

    Actionsactions that appear on the context menu when the node is right-clicked, which can be invoked

    by the userIn the preceding tutorial, you used your EventChildFactory class to create Nodes, by calling

    new AbstractNode(Children.create(new EventChildFactory(), true),

    Lookups.singleton(key))

    and then calling setDisplayName(key.toString()) to provide a basic display name. There is much more

    that can be done to make your Nodes more user-friendly. First you will need to create a Node subclass to work

    with, as instructed below.

    1. In the My Editor project, right click the package org.myorg.myeditor and choose New > Java Class.

    Wiki

    NetBeans Platform

    Wiki

    WikiHomePage

    WikiHomePage

    Project Links Screenshots

    Customer

    Testimonials

    Quick Start

    About thisProjectPlatform was

    started in

    November 2009, isowned by Antonin

    Nebuzelsky, and

    has 142 members.

    Join This Project

    NetBeans.orgJoin

    News

    Releases &

    Planning

    Mailing Lists

    Bugzilla

    Contribute

    Teams

    Guidelines

    https://netbeans.org/community/guidelines/https://netbeans.org/community/teams/https://netbeans.org/community/contribute/https://netbeans.org/community/issues.htmlhttps://netbeans.org/community/lists/https://netbeans.org/community/releases/https://netbeans.org/community/news/https://netbeans.org/people/newhttps://netbeans.org/projects/platform/watchhttps://netbeans.org/projects/platform/membershttps://netbeans.org/people/4-Antonin-Nebuzelskyhttps://netbeans.org/projects/platformhttp://platform.netbeans.org/tutorials/nbm-google.htmlhttp://platform.netbeans.org/testimonials.htmlhttp://platform.netbeans.org/screenshots.htmlhttps://netbeans.org/projects/platform/pages/Homehttps://netbeans.org/projects/platform/pages/Homehttps://platform.netbeans.org/tutorials/nbm-selection-2.htmlhttp://java.net/projects/nb-api-samples/sources/api-samples/show/versions/8.0/tutorials/selection-management/3-of-4/EventManagerhttp://java.sun.com/javase/downloads/index.jsphttps://netbeans.org/downloads/index.htmlhttp://-/?-http://-/?-http://-/?-http://-/?-http://-/?-
  • 8/10/2019 3.NetBeans Nodes API Tutorial

    3/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 3/22

    Name the class "EventNode" and press Enter or click Finish.

    2. Change the signature and constructors of the class as follows:

    package org.myorg.myeditor

    import org.myorg.myapi.Event

    import org.openide.nodes.AbstractNode

    import org.openide.nodes.Childrenimport org.openide.util.lookup.Lookups

    public class EventNode extends AbstractNode {

    public EventNode(Event obj) {

    super (Children.create(new EventChildFactory(), true),

    Lookups.singleton(obj))

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

    }

    public EventNode() { super (Children.create(new EventChildFactory(), true))

    setDisplayName ("Root")

    }

    }

    3. Open MyEditor from the same package, in the code editor. Remove these lines in the constructor:

    mgr.setRootContext(new AbstractNode(new EventChildFactory()))

    setDisplayName ("My Editor")

    Instead of the above, add this single line of code:

    mgr.setRootContext(new EventNode())

    4. Now make a similar change to the EventChildFactory class. Open it in the editor, and change its

    createNodeForKey method as follows:

    @Overrideprotected Node createNodeForKey(Event key) {

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    4/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 4/22

    return new EventNode(key)}

    The code is now runnable, but so far all you've done is moved logic around. It will do exactly what it did before.

    The only (non-user-visible) difference you now are using a Node subclass instead of just using AbstractNode.

    Enhancing Display Names with HTML

    The first enhancement you will provide is an enhanced display name. The Nodes API supports a limited subset ofHTML which you can use to enhance how the labels for Nodes are shown in Explorer UI components. The

    following tags are supported:

    font colorfont size and face settings are not supported, but color is, using standard html syntax

    font style tagsb,i,u and s tagsbold, italic, underline, strikethrough

    A limited subset of SGML entities: &quot, &lt, &amp, &lsquo, &rsquo, &ldquo, &rdquo, &ndash,

    &mdash, &ne, &le, &ge, &copy, &reg, &trade, and &nbsp

    Since there is no terribly exciting data available from your Event, which only has an integer and a creation

    date, you'll extend this artificial example, and decide that odd numbered Events should appear with blue text.

    1. Add the following method to EventNode:

    @Override

    public String getHtmlDisplayName() {

    Event obj = getLookup().lookup (Event.class)

    if (obj!=null && obj.getIndex() % 2 != 0) {

    return "Event " + obj.getIndex() + ""

    } else {

    return null

    }

    }

    2. What the above code accomplishes is thiswhen painting, the Explorer component showing the nodes

    calls getHtmlDisplayName() first. If it gets a non-null value back, then it will use the HTML string it

    received and a fast, lightweight HTML renderer to render it. If it is null, then it will fall back to whatever

    is returned by getDisplayName(). So this way, any EventNode whose Event has an index not

    divisible by 2 will have a non-null HTML display name. Run the Event Manager again and you should

    see the following:

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    5/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 5/22

    There are two reasons for getDisplayName() and getHtmlDisplayName() being separate methodsfirst, it

    is an optimization second, as you will see later, it makes it possible to compose HTML strings together, without

    needing to strip marker tags.

    You can enhance this furtherin the previous tutorial, the date was included in the HTML string, and you haveremoved it here. So let's make your HTML string a little more complex, and provide HTML display names for all

    of your nodes.

    1. Modify the getHtmlDisplayName() method as follows:

    @Override

    public String getHtmlDisplayName() {

    Event obj = getLookup().lookup (Event.class)

    if (obj != null) {

    return "Event " + obj.getIndex() + "" + " " + obj.getDate() + ""

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    6/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 6/22

    } else {

    return null

    }

    }

    2. Run the Event Manager again and now you should see the following:

    One minor thing you can do to improve appearance hereyou are currently using hard-coded colors in your

    HTML. Yet the NetBeans Platform can run under various look and feels, and there's no guarantee that your hard-

    coded color will not be the same as or very close to the background color of the tree or other UI component

    your Node appears in.

    The NetBeans HTML renderer provides a minor extension to the HTML spec which makes it possible to look up

    colors by passing UIManager keys. The look and feel Swing is using provides a UIManager, which manages a

    name-value map of the colors and fonts a given look and feel uses. Most (but not all) look and feels find the

    colors to use for different GUI elements by calling UIManager.getColor(String), where the string key issome agreed-upon value. So by using values from UIManager, you can guarantee that you will always be

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    7/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 7/22

    producing readable text. The two keys you will use are "textText", which returns the default color for text

    (usually black unless using a look and feel with a dark-background theme), and "controlShadow" which should

    give us a color that contrasts, but not too much, with the default control background color.

    1. Modify the getHtmlDisplayName() method as follows:

    @Override

    public String getHtmlDisplayName() { Event obj = getLookup().lookup (Event.class)

    if (obj != null) {

    return "Event " + obj.getIndex() + ""

    +

    " " + obj.getDate() + "

    "

    } else {

    return null

    }

    }

    2. Run the Event Manager again and now you should see the following:

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    8/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 8/22

    Note: You got rid of your blue color and switched to plain old black. Using the value of

    UIManager.getColor("textText") guarantees us text that will always be readable under any look and

    feel, which is valuable also, color should be used sparingly in user interfaces, to avoid the angry fruit salad

    effect. If you really want to use wilder colors in your UI, the best bet is to either find a UIManager

    key/value pair that consistently gets what you want, or create a ModuleInstall class and derive the color

    from a color you can get from UIManager, or if you are sure you know the color theme of the look and feel,

    hard-code it on a per-look and feel basis ( if

    ("aqua".equals(UIManager.getLookAndFeel().getID())...).

    Providing Icons

    Icons, used judiciously, also enhance user interfaces. So providing 16x16 pixel icon is another way to improve

    the appearance of your UI. One caveat of using icons is, do not attempt to convey too much information via an

    iconthere are not a lot of pixels there to work with. A second caveat that applies to both icons and display

    names is, never use only color to distinguish a node there are many people in the world who are colorblind.

    Providing an icon is quite simpleyou just load an image and set it. You will need to have a GIF or PNG file to

    use. If you do not have one easily available, here is one you can use:

    http://core.netbeans.org/source/browse/*checkout*/core/swing/plaf/src/org/netbeans/swing/plaf/util/RelativeColor.javahttp://wiki.netbeans.org/wiki/view/DevFaqModulesGeneralhttp://www.catb.org/jargon/html/A/angry-fruit-salad.html
  • 8/10/2019 3.NetBeans Nodes API Tutorial

    9/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 9/22

    1. Copy the image linked above, or another 16x16 PNG or GIF, into the same package as the MyEditor

    class.

    2. Add the following method to the EventNode class:

    @Override

    public Image getIcon (int type) {

    return ImageUtilities.loadImage ("org/myorg/myeditor/icon.png")

    }

    Note: It is possible to have different icon sizes and stylesthe possible int values passed to

    getIcon() are constants on java.beans.BeanInfo, such as BeanInfo.ICON_COLOR_16x16.

    Also, while you can use the standard JDK ImageIO.read() to load your images,

    ImageUtilities.loadImage() is more optimized, has better caching behavior, and supports

    branding of images.

    3. If you run the code now, you will notice one thingthe icon is used for some nodes but not others!

    The reason for this is that it is common to use a different icon for an unexpanded versus an expanded

    Node. All you need to do to fix this is to override another method. Add the following additional method

    to the EventNode:

    @Override

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    10/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 10/22

    public Image getOpenedIcon(int i) {

    return getIcon (i)}

    Now if you run the Event Manager, all of the Nodes will have the correct icon, as shown below:

    Actions and Nodes

    The next aspect of Nodes you will treat isActions. A Node has a popup menu which can contain actions that theuser can invoke against that Node. Any subclass of javax.swing.Action can be provided by a Node, and will

    show up in its popup menu. Additionally, there is the concept of presenters, which you will cover later.

    First, let's create a simple action for your nodes to provide:

    1. Override the getActions() method of EventNode as follows:

    @Override

    public Action[] getActions (boolean popup) {

    return new Action[] { new MyAction() }

    }

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    11/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 11/22

    2. Now, create the MyAction class as an inner class of EventNode:

    private class MyAction extends AbstractAction {

    public MyAction () {

    putValue (NAME, "Do Something")

    }

    @Override public void actionPerformed(ActionEvent e) {

    Event obj = getLookup().lookup(Event.class)

    JOptionPane.showMessageDialog(null, "Hello from " + obj)

    }

    }

    3. Run the Event Manager again and notice that when you right-click on a node, a menu item is shown:

    When you select the menu item, the action is invoked:

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    12/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 12/22

    Presenters

    Of course, sometimes you will want to provide a submenu or checkbox menu item or some other component,

    other than a JMenuItem, to display in the popup menu. This is quite easy:

    1. Add to the signature of MyAction that it implements Presenter.Popup:

    private class MyAction extends AbstractAction implements Presenter.Popup {

    Press Ctrl-Shift-I to fix imports.

    2. Position the caret in the class signature line of MyAction and press Alt-Enter when the lightbulb glyph

    appears in the margin, and accept the hint "Implement All Abstract Methods". Implement the newly

    created method getPopupPresenter() as follows:

    @Override

    public JMenuItem getPopupPresenter() {

    JMenu result = new JMenu("Submenu") //remember JMenu is a subclass ofJMenuItem

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    13/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 13/22

    result.add (new JMenuItem(this))

    result.add (new JMenuItem(this))

    return result

    }

    3. Run the Event Manager again and notice that you now have the following:

    The result is not too excitingyou now have a submenu called "Submenu" with two identical menu items. But

    again, you should get the idea of what is possible hereif you want to return a JCheckBoxMenuItem or some

    other kind of menu item, it is possible to do that.

    Properties and the Property Sheet

    The last subject you'll cover in this tutorial is properties. You are probably aware that NetBeans IDE contains a

    "property sheet" which can display the "properties" of a Node. What exactly "properties" means depends on how

    the Node is implemented. Properties are essentially name-value pairs which have a Java type, which are

    grouped in sets and shown in the property sheetwhere writable properties can be edited via their property

    editors (see java.beans.PropertyEditor for general information about property editors).

    So, built into Nodes from the ground up is the idea that a Node may have properties that can be viewed and,

    optionally, edited on a property sheet. Adding support for this is quite easy. There is a convenience class in the

    Nodes API, Sheet, which represents the entire set of properties for a Node. To it you may add instances of

    Sheet.Set, which represent "property sets", which appear in the property sheet as groups of properties.

    1. Override EventNode.createSheet() as follows:

    http://java.sun.com/j2se/1.4.2/docs/api/java/beans/PropertyEditor.html
  • 8/10/2019 3.NetBeans Nodes API Tutorial

    14/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 14/22

    @Override

    protected Sheet createSheet() {

    Sheet sheet = Sheet.createDefault()

    Sheet.Set set = Sheet.createPropertiesSet()

    Event obj = getLookup().lookup(Event.class)

    try {

    Property indexProp = new PropertySupport.Reflection(obj,

    Integer.class, "getIndex", null)

    Property dateProp = new PropertySupport.Reflection(obj, Date.class,

    "getDate", null)

    indexProp.setName("index")

    dateProp.setName("date")

    set.put(indexProp)

    set.put(dateProp)

    } catch (NoSuchMethodException ex) {

    ErrorManager.getDefault()

    }

    sheet.put(set)

    return sheet

    }

    Press Ctrl-Shift-I to Fix Imports.

    2. Right click the EventManager and choose Run and then, once it is started up, select Window > IDE

    Tools > Properties to show the NetBeans Platform Properties window.

    3. Move the selection between different nodes, and notice the property sheet updating, just as your

    MyViewer component does, as shown below:

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    15/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 15/22

    The above code makes use of a very convenient class: PropertySupport.Reflection, which may simply be

    passed an object, a type, and getter and setter method names, and it will create a Property object that can read

    (and optionally write) that property of the object in question. So you use PropertySupport.Reflection a

    simple way to wire one Property object up to the getIndex() method of Event.

    If you want Property objects for nearly all of the getters/setters on an underlying model object, you may want

    to use or subclass BeanNode, which is a full implementation of Node that can be given a random object and will

    try to create all the necessary properties for it (and listen for changes) via reflection (how exactly they are

    presented can be controlled by creating a BeanInfo for the class of the object to be represented by the node).

    Caveat: Setting the name of your properties is very important. Property objects test their equality

    based on names. If you are adding some properties to a Sheet.Set and they seem to be

    disappearing, very probably their name is not setso putting one property in a HashSet with the

    same (empty) name as another is causing later added ones to displace earlier added ones.

    Read-Write Properties

    To play with this concept further, what you really need is a read/write property. So the next step is to add some

    additional support to Event to make the Date property settable.

    1. Open org.myorg.myapi.Event in the code editor.

    2. Remove the final keyword from the line declaring the date field

    3. Add the following setter and property change support methods to Event:

    http://java.sun.com/j2se/1.4.2/docs/api/java/beans/BeanInfo.html
  • 8/10/2019 3.NetBeans Nodes API Tutorial

    16/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 16/22

    private List listeners = Collections.synchronizedList(new LinkedList())

    public void addPropertyChangeListener (PropertyChangeListener pcl) {

    listeners.add (pcl)

    }

    public void removePropertyChangeListener (PropertyChangeListener pcl) {

    listeners.remove (pcl)

    }

    private void fire (String propertyName, Object old, Object nue) {

    //Passing 0 below on purpose, so you only synchronize for one atomic

    call:

    PropertyChangeListener[] pcls = (PropertyChangeListener[])

    listeners.toArray(new PropertyChangeListener[0])

    for (int i = 0 i < pcls.length i++) {

    pcls[i].propertyChange(new PropertyChangeEvent (this, propertyName,

    old, nue))

    }

    }

    4. Now, within the Event, call the fire method above:

    public void setDate(Date d) {

    Date oldDate = date

    date = d

    fire("date", oldDate, date)

    }

    5. In EventNode.createSheet(), change the way dateProp is declared, so that it will be writable as

    well as readable:

    Property dateProp = new PropertySupport.Reflection(obj, Date.class, "date")

    Now, rather than specifying explicit getters and setters, you are just providing the property name, and

    PropertySupport.Reflection will find the getter and setter methods for us (and in fact it will also

    find the addPropertyChangeListener() method automatically).

    6. Re-run the module Event Manager, and notice that you can now select an instance ofEventNode

    in

    MyEditor and actually edit the date value, as shown below:

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    17/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 17/22

    Note: The result is persisted when you restart the IDE.

    However, there is still one bug in this codewhen you change the Date property, you should also update the

    display name of your node. So you will make one more change to EventNode and have it listen for property

    changes on Event.

    1. Modify the signature of EventNode so that it implements java.beans.PropertyChangeListener:

    public class EventNode extends AbstractNode implements PropertyChangeListener

    {

    Press Ctrl-Shift-I to Fix Imports.

    2. Placing the caret in the signature line, accept the hint "Implement All Abstract Methods".

    3. Add the following line to the constructor which takes an argument of Event:

    obj.addPropertyChangeListener(WeakListeners.propertyChange(this, obj))

    Note: Here you are using a utility method on org.openide.util.WeakListeners. This is a

    technique for avoiding memory leaksan Event will only weakly reference its EventNode, so if

    the Node's parent is collapsed, the Node can be garbage collected. If the Node were still

    referenced in the list of listeners owned by Event, it would be a memory leak. In your case, the

    Node actually owns the Event, so this is not a terrible situationbut in real world programming,

    objects in a data model (such as files on disk) may be much longer-lived than Nodes displayed to

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    18/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 18/22

    the user. Whenever you add a listener to an object which you never explicitly remove, it is

    preferable to use WeakListenersotherwise you may create memory leaks which will be quite a

    headache later. If you instantiate a separate listener class, though, be sure to keep a strong

    reference to it from the code that attaches itotherwise it will be garbage collected almost as soon

    as it is added.

    4. Finally, implement the propertyChange() method:

    @Overridepublic void propertyChange(PropertyChangeEvent evt) {

    if ("date".equals(evt.getPropertyName())) {

    this.fireDisplayNameChange(null, getDisplayName())

    }

    }

    5. Run the module Event Manager again, select a EventNode in the MyEditor window and change its

    Date propertynotice that the display name of the Node is now updated correctly, as shown below,

    where the year 2009 and is now reflected both on the node and in the property sheet:

    Grouping Property Sets

    You may have noticed when running Matisse, NetBeans IDE's form editor, that there is a set of buttons at the

    top of the property sheet, for switching between groups of property sets.

    Generally this is only advisable if you have a really large number of properties, and generally it's not advisable

    for ease-of-use to have a really large number of properties. Nonetheless, if you feel you need to split out yoursets of properties into groups, this is easy to accomplish.

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    19/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 19/22

    Property has the methods getValue() and setValue(), as does PropertySet (both of them inherit this

    from java.beans.FeatureDescriptor). These methods can be used in certain cases, for passing ad-hoc

    "hints" between a given Property or PropertySet and the property sheet or certain kinds of property editor

    (for example, passing a default filechooser directory to an editor for java.io.File). And that is the technique

    by which you can specify a group name (to be displayed on a button) for one or more PropertySets. In real

    world coding, this should be a localized string, not a hard-coded string as below:

    1. Open EventNode in the code editor

    2. Modify the method createSheet() as follows (modified and added lines are highlighted):

    @Override

    protected Sheet createSheet() {

    Sheet sheet = Sheet.createDefault()

    Sheet.Set set = Sheet.createPropertiesSet()

    Sheet.Set set2 = Sheet.createPropertiesSet()

    set2.setDisplayName("Other")

    set2.setName("other")

    Event obj = getLookup().lookup (Event.class)

    try {

    Property indexProp = new PropertySupport.Reflection(obj,

    Integer.class, "getIndex", null)

    Property dateProp = new PropertySupport.Reflection(obj,

    Date.class, "date")

    indexProp.setName("index")

    dateProp.setName ("date") set.put (indexProp)

    set2.put (dateProp)

    set2.setValue("tabName", "Other Tab")

    } catch (NoSuchMethodException ex) {

    ErrorManager.getDefault()

    }

    sheet.put(set)

    sheet.put(set2) return sheet

    http://java.sun.com/j2se/1.4.2/docs/api/java/beans/FeatureDescriptor.html
  • 8/10/2019 3.NetBeans Nodes API Tutorial

    20/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 20/22

    }

    3. Run the Event Manager again, and notice that there are now buttons at the top of the property sheet,

    and there is one property under each, as seen here:

    General Property Sheet Caveats

    If you used NetBeans 3.6 or earlier, you may notice that older versions of NetBeans employed the property

    sheet very heavily as a core element of the UI, whereas it's not so prevalent today. The reason is simple

    property sheet based UIs are not terribly user-friendly. That doesn't mean don't use the property sheet, but

    use it judiciously. If you have the option of providing a customizer with a nice GUI, such as via JavaFX, do so

    your users will thank you.

    And if you have an enormous number of properties on one object, try to find some overall settings that

    encapsulate the most probable combinations of settings. For example, think of what the settings for a tool for

    managing imports on a Java class can beyou can provide integers for setting the threshold number of usages

    of a package required for wildcard imports, the threshold number of uses of a fully qualified class name required

    before importing it at all, and lots of other numbers ad nauseum. Or you can ask yourself the question, what is

    the user trying to do?. In this case, it's either going to be getting rid of import statements or getting rid of fully

    qualified names. So probably settings of low noise, medium noise and high noise where "noise" refers to the

    amount of fully qualified class/package names in the edited source file would do just as well and be much easier

    to use. Where you can make life simpler for the user, do so.

    Review of Concepts

    This tutorial has sought to get across the following ideas:

    Nodes are a presentation layer.

    The display names of Nodes can be customized using a limited subset of HTML.

  • 8/10/2019 3.NetBeans Nodes API Tutorial

    21/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 21/22

    Send Us Your Feedback

    Nodes have icons, and you can provide custom icons for nodes you create.

    Nodes have Actions an Action which implements Presenter.Popup can provide its own component to

    display in a popup menu the same is true for main menu items using Presenter.Menu, and toolbar

    items using Presenter.Toolbar.

    Nodes have properties, which can be displayed on the property sheet.

    Next Steps

    You've now begun to delve into how to get more out of the property sheet in

    NetBeans. In the next tutorial, you will cover how to write custom editors and provide a custom inline editor for

    use in the property sheet.

    SiteMapAbout Us

    https://netbeans.org/about/index.htmlhttps://netbeans.org/sitemaps/www_map.htmlhttps://platform.netbeans.org/tutorials/nbm-property-editors.htmlhttp://www.facebook.com/NetBeanshttps://netbeans.org/about/contact_form.html?to=3&subject=Feedback:%20Nodes%20API%208.0%20Module%20Tutorial
  • 8/10/2019 3.NetBeans Nodes API Tutorial

    22/22

    8/29/2014 NetBeans Nodes API Tutorial for the NetBeans Platform

    https://platform.netbeans.org/tutorials/nbm-nodesapi2.html 22/22

    Contact

    Legal & Licences

    By use of this website, you agree to the NetBeans Policies and Terms of Use (revision 20140718.4a68f04). 2014, Oracle Corporationand/or its affiliates. Sponsored by

    https://netbeans.org/projects/help/pages/ReleaseNoteshttps://platform.netbeans.org/about/legal/terms-of-use.htmlhttps://netbeans.org/about/legal/index.htmlhttps://netbeans.org/about/contact.htmlhttps://twitter.com/netbeanshttps://plus.google.com/105597468329838196909/http://www.youtube.com/user/netbeansvideos