Wednesday, February 8, 2017

Manually expanding or selecting a node in a dynamically updated JTree

The UI component that is famously used to represent hierarchical data is JTree in Java based desktop applications. It is very common need to change or alter the underlying data model to either add, update or delete nodes in the tree structure.

While dynamically updating underlying tree data model, visually it is a common need to expand or select the newly added nodes. To do this,  JTree and underlying TreeModel supports many functions to expand the path or select a path. But, sometimes this simply may or may not work. The reasons could be that we are not updating the tree in right way or some of the life cycle methods are not executed correctly when dynamically updating the tree. In these cases, we can either manually expand a path or select a path. The code snippet below shows how to do it.



Above code snippet assumes that, you have a tree constructed and you know the node that needs to either expanded or selected. One can just pass these objects and achieve the expected result.

Please note, we got to do this in a legacy project, where tree node selection was not working when the tree got updated dynamically. We took this approach in order to avoid total overhaul of the tree construction logic due to time and cost limitations. But, in a properly constructed tree, just using the default API methods we should be to achieve the expected result.