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.

You can easily change the font attributes like bold and italic of a JTree‘s tree node (parent or leaf node) by overriding the DefaultTreeCellRenderer class getTreeCellRendererComponent() method. Then you can set the JTree’s setRenderer() method to this renderer object.

The code above sets the tree node’s font attributes (in this case bold and italic) if it is selected. If you want all tree nodes to have these same font attributes, you can remove the if condition statement.

To get the selected node value of JTree, you need to add a selection listener in order to be able to detect selections when a node of a JTree has focus (selected) or not. The code below adds a TreeSelectionListener and uses the getLastPathComponent() method of a TreePath object to get the text of the JTree node selected.

Remember that a TreePath contains an array of Objects that refers to the nodes starting from the root until the last one called the leaf.

Related Posts Plugin for WordPress, Blogger...