Disabling the collapse event of the JTree is possible by adding a listener to it. There may be times where you want your JTree to be always in expanded mode hence disabling its collapse event is the only way to go.

Add a TreeWillExpandListener to the JTree, make the treeWillCollapse() method throw ExpandVetoException and that should do it.

The sample data of the JTree when you drag it to your container always appear as color, sports and food. You cannot find this in the uneditable initComponents() method of the class file. Instead, go to the property list of the JTree class and do the following:

  • go to the “model” property and you will see a [TreeModel] value
  • click on the [TreeModel] to open a dialog
  • under the Tree Model Editor dropdown you will see the sample data below
  • delete everything on the left pane and click ok

That’s it. Pretty simple right?

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.

Related Posts Plugin for WordPress, Blogger...