No Expansion Icon When No Children (Part 2)

In part 1, the problem of the superfluous expansion icon is discussed and solved. However, the solution is incomplete as Michael Bishop indicates in the comment to part 1:

I recently implemented this solution. The explorer tree appeared correctly, but no longer updates correctly; adding and removing nodes don't seem to be triggering the refresh() method in the factory class. For instance, when adding a new child, the underlying data model updates and I can confirm the child is added, but nothing happens in the tree.

The solution to the above is to (1) detect when a new child is added and to (2) then call Node.setChildren to update the node hierarchy. Set a PropertyChangeListener on the node and then call setChildren when you detect that a new child has been added.

@Override
public void propertyChange(PropertyChangeEvent evt) {
    if (evt.getPropertyName().equals("ADD")) {
        setChildren(Children.create(new ObjectChildFactory(bean), false));
    }
} 

This technique lets you show the user the true hierarchical state of each node, i.e., only if a node has children is an expansion icon shown.

The whole solution, i.e., a complete application that shows all the pieces fitted together, is available here:

https://java.net/projects/nb-api-samples/sources/api-samples/show/versions/7.3/misc/ObjectViewer

Comments:

It might be worth noting that the Callable class determines whether or not there are children. A more robust solution might detect a "children changed" event and call setChildren using the Callable (as done in the original constructor to the node).

Otherwise, things might start to fall apart on "remove" events since you have to determine if there are any children left and if so, use Children.LEAF.

In fact, I think you have to call setChildren() in only two cases ideally:

- When going from 0 to 1+ children. (Setting a factory)
- When going from 1+ children to 0 children. (Setting a leaf)

I'll be working with this in my project and will try to update the sample project accordingly.

Posted by Michael Bishop on May 26, 2013 at 08:21 PM PDT #

Great! Yes, make changes to the sample project as needed.

Posted by Geertjan on May 27, 2013 at 03:02 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
12
13
14
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today