Dynamically Updating NetBeans Platform Explorer Trees With Expansion Icons
Join the DZone community and get the full member experience.
Join For FreeThe purpose of this article is to expand on Geertjan's blog entries about explorer trees and expansion icons. The first article found at https://blogs.oracle.com/geertjan/entry/no_expansion_key_when_no works well for static trees. When a node is constructed, it determines whether or not the underlying data object or bean has children. If there are no children, it becomes a leaf node. If there are children, it can be expanded to show its children. This works well for static trees, but in this example, the decision is only made once. If a node is determined to be a leaf node, but the underlying bean later adds a child, the node remains a leaf node.
The second article almost gets us there. It can be found at https://blogs.oracle.com/geertjan/entry/no_expansion_icon_when_no. When a child is added, the change is detected. Once a child is added, the node employs the use of a node factory and continues to do so. But if all the children are removed, the node does not become a leaf.
The solution is to track two states of our parent node. We want to know whether or not the node has children when it's created. We also want to know whether or not the node has children when children are added or removed.
Let's take a look at the underlying bean, MyObject:
public class MyObject { public static final String ADD_CHILD = "ADD"; public static final String CHILDREN_TYPE = "CHILDREN"; public static final String LABEL_TYPE = "LABEL"; public static final String REMOVE_CHILD = "REMOVE"; private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); private final MyObject parent; private String label; private List children = new ArrayList(); public MyObject(final MyObject parent, final String label) { this.parent = parent; this.label = label; } public MyObject(final String label) { this(null, label); } public void addChild(final MyObject child) { final boolean oldState = this.hasChildren(); final int oldChildren = children.size(); children.add(child); propertyChangeSupport.firePropertyChange( CHILDREN_TYPE, oldState, this.hasChildren()); propertyChangeSupport.firePropertyChange( ADD_CHILD, oldChildren, children.size()); } public List getChildren() { return children; } public MyObject getParent() { return parent; } public String getLabel() { return label; } public boolean hasChildren() { return !children.isEmpty(); } public boolean hasParent() { return parent != null; } public void removeChild(final MyObject child) { final boolean oldState = this.hasChildren(); final int oldChildren = children.size(); children.remove(child); propertyChangeSupport.firePropertyChange( CHILDREN_TYPE, oldState, this.hasChildren()); propertyChangeSupport.firePropertyChange( REMOVE_CHILD, oldChildren, children.size()); } public void setLabel(String label) { final String oldLabel = this.label; this.label = label; propertyChangeSupport.firePropertyChange(LABEL_TYPE, oldLabel, label); } public void addPropertyChangeListener( final PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } /** * Remove PropertyChangeListener. * * @param listener */ public void removePropertyChangeListener( final PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } }This is a basic bean that has integrated property change support. A label for the object is stored, as well as an optional parent object. It also maintains a list of children. When changes occur in this bean, it fires the appropriate property change. There are four:
- LABEL_TYPE is fired if the label field of the bean changes.
- ADD_CHILD is fired when new children are added.
- REMOVE_CHILD is fired when children are removed.
- CHILDREN_TYPE is fired when the bean goes from having children to having no children or vice-versa. This works because PropertyChangeSupport objects do not fire events when the oldValue and newValue parameters are the same. So even though this event is triggered every time a child is added or removed, listeners will only receive a PropertyChangeEvent when the two values differ.
public class ObjectNode extends BeanNode implements PropertyChangeListener { private MyObject bean; public ObjectNode(MyObject bean) throws IntrospectionException { super(bean, Children.createLazy(new ObjectCallable(bean)), Lookups.singleton(bean)); this.bean = bean; this.setDisplayName(bean.getLabel()); bean.addPropertyChangeListener(this); } public final void checkChildren(final Object eventObject) { if (eventObject == Boolean.TRUE) { this.setChildren(Children.create( new ObjectChildFactory(bean), false)); } else if (eventObject == Boolean.FALSE) { this.setChildren(Children.LEAF); } } @Override public Action[] getActions(final boolean popup) { final Action[] returnActions = new Action[2]; returnActions[0] = new AddAction(bean); returnActions[1] = new RemoveAction(bean); return returnActions; } @Override public Action getPreferredAction() { return new AddAction(bean); } @Override public void propertyChange(final PropertyChangeEvent evt) { if (evt.getPropertyName().equals(MyObject.LABEL_TYPE)){ setDisplayName(bean.getLabel()); } // We need to see if we have to update our children. else if (MyObject.CHILDREN_TYPE.equals(evt.getPropertyName())) { this.checkChildren(evt.getNewValue()); } } }In the constructor, we use a Callable object (ObjectCallable) to determine whether or not we have children in the starting state. We'll look at that in a minute. ObjectNode also listens for property changes.
- If the label changes, ObjectNode updates the display name.
- If the state of having children (true/false) changes, we update how the node's children are represented.
We also have two actions; one to add child nodes and one to remove a node. We'll get to these later as well. The default action (triggered by double-clicking the node) is to add a new child node.
ObjectCallable is very similar to the checkChildren method.
public class ObjectCallable implements Callable { private final MyObject key; public ObjectCallable(final MyObject key) { this.key = key; } @Override public Children call() throws Exception { if (!key.hasChildren()) { return Children.LEAF; } else { return Children.create(new ObjectChildFactory(key), true); } } }
If you've worked with NodeFactory objects before, ObjectChildFactory is pretty basic.
public class ObjectChildFactory extends ChildFactory.Detachableimplements PropertyChangeListener { private MyObject key; public ObjectChildFactory(final MyObject key) { this.key = key; key.addPropertyChangeListener(this); } @Override protected boolean createKeys(List toPopulate) { final List children = key.getChildren(); for (MyObject child : children) { toPopulate.add(child); } return true; } @Override protected Node createNodeForKey(MyObject key) { ObjectNode node = null; try { node = new ObjectNode(key); } catch (IntrospectionException ex) { Exceptions.printStackTrace(ex); } return node; } @Override public void propertyChange(final PropertyChangeEvent evt) { if (MyObject.ADD_CHILD.equals(evt.getPropertyName())) { this.refresh(true); } else if (MyObject.REMOVE_CHILD.equals(evt.getPropertyName())) { this.refresh(true); } } }
ObjectNodeFactory registers itself as a PropertyChangeListener on the node it's creating child nodes for. It listens for the ADD_CHILD and REMOVE_CHILD events and triggers a refresh when one is fired. This way, the explorer tree stays in sync with the state of the underlying bean model.
This action is executed from a node's context menu or by double-clicking a node. It adds a new child to the node with the label being the value of System.currentTimeMillis().
public class AddAction extends AbstractAction { private final MyObject bean; public AddAction(final MyObject bean) { this.bean = bean; this.putValue(AbstractAction.NAME, "Add Node"); } @Override public void actionPerformed(final ActionEvent evt) { bean.addChild( new MyObject(bean, String.valueOf(System.currentTimeMillis()))); } }
This action is executed from a node's context menu. When a node is selected to be removed, we find the parent and remove the node as a child. If the node has no parent, we inform the user and don't remove the node.
public class RemoveAction extends AbstractAction { private final MyObject bean; public RemoveAction(final MyObject bean) { this.bean = bean; this.putValue(AbstractAction.NAME, "Remove Node"); } @Override public void actionPerformed(final ActionEvent event) { if (bean.hasParent()) { final MyObject parent = bean.getParent(); parent.removeChild(bean); } else { JOptionPane.showMessageDialog( null, "The head node cannot be removed!"); } } }
This is the explorer tree that will be shown when the platform application is started. It begins with a single head node "parent" and adds the first child to it, appropriately called "first." The root context of the explorer is set to be the "parent" node and the rest of our code takes over from there.
@TopComponent.Description( preferredID = "ObjectExplorerTopComponent", persistenceType = TopComponent.PERSISTENCE_ALWAYS) @TopComponent.Registration(mode = "explorer", openAtStartup = true) @ActionID(category = "Window", id = "org.o.explorer.ObjectExplorerTopComponent") @ActionReference(path = "Menu/Window") @TopComponent.OpenActionRegistration( displayName = "#CTL_ObjectExplorerAction", preferredID = "ObjectExplorerTopComponent") @Messages({ "CTL_ObjectExplorerAction=ObjectExplorer", "CTL_ObjectExplorerTopComponent=ObjectExplorer Window", "HINT_ObjectExplorerTopComponent=This is a ObjectExplorer window" }) public final class ObjectExplorerTopComponent extends TopComponent implements ExplorerManager.Provider { private ExplorerManager em = new ExplorerManager(); private MyObject parent = new MyObject("parent"); public ObjectExplorerTopComponent() throws IntrospectionException { initComponents(); setName(Bundle.CTL_ObjectExplorerTopComponent()); setToolTipText(Bundle.HINT_ObjectExplorerTopComponent()); setLayout(new BorderLayout()); parent.addChild(new MyObject("First")); em.setRootContext(new ObjectNode(parent)); add(new BeanTreeView(), BorderLayout.CENTER); associateLookup(ExplorerUtils.createLookup(em, getActionMap())); } @Override public ExplorerManager getExplorerManager() { return em; } }
So in order to make a truly dynamic explorer tree that will properly maintain state and show expansion icons across adds and removes, we've done the following work:
- Made our bean (MyObject) communicate when it adds and removes children. It also fires a different event when we go from having children to having none and vice-versa.
- Made our node (ObjectNode) determine the state of its children when it's constructed (ObjectCallable) AND when the state of the children changes (PropertyChangeEvent/Listener). It knows how to change from a leaf to a factory when necessary (checkChildren).
- Made our factory refresh when nodes are added and removed.
- Implemented basic add and remove functionality.
These paradigms can be reused in other projects that have dynamic explorer trees. From here, more robust and detailed functionality can be grafted on. This project should serve as a good starting point.
Opinions expressed by DZone contributors are their own.
Trending
-
DZone's Article Submission Guidelines
-
Is Podman a Drop-In Replacement for Docker?
-
Effective Java Collection Framework: Best Practices and Tips
-
Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
Comments