Here is a useful method to convert an org.w3c.dom.Node object to String representation. node.toString() does not work. Well, it may give you a String but not the one that you would expect, such as a set of xml tags. What you need to use is the Transformer class.

A very important thing to note is that the transformer.setOutputProperty() must be called with OMIT_XML_DECLARATION set to yes so that the string <?xml version=”1.0″ encoding=”UTF-8″?> will not be added to the output.

The JTree class does not have a means to save a tree node’s state (e.g. expanded of collapsed). I did come across a forum where a post mentioned about the use of a TreeExpansionListener to save a tree node’s state and provided a short sample snippet. I modified some minor bugs and the code below is the finished and modified code.

Say you want to add a new tree node, you do not want the JTree to refresh all its tree nodes’ expanded state to collapsed. Rather, the previous state will still be the same even when a new tree node is added to the JTree. You can call the method jTree1.restoreExpansionState() to restore it and jTree1.resetExpansionState() to reset all the state to collapsed.

jtreeI have read a number of articles that featured source codes from forums and sites on how to show or hide nodes of a JTree. The easiest code that I found that was easy to understand and use are source files labeled InvisibleNode.java and InvisibleTreeModel.java.

You can easily search that in Google to get those files. The result that I wanted to accomplish was to show only 2 checkbox leaf nodes at most if the last leaf node of the parent node has a button labeled HIDE and is clicked. I know it is hard to visualize so I included a snapshot of my JTree.

My JTree‘s parent nodes contain leaf nodes that have checkboxes and a button at the end of each parent node if there consists more than 2 checkbox leaf nodes per parent node. By default the button is labeled HIDE. If I click on it, it will show only 2 checkboxes while hiding the rest (except the button) and the button’s label will change to SHOW. If I click on the button again, it will all all sibling leaf nodes.

Those two Java source files easily did the trick in hiding and showing tree nodes.

Related Posts Plugin for WordPress, Blogger...