How to search a particular node in jtree and make that node expanded.?

Expanding on @mKorbel’s answer and as discussed in How to Use Trees, you can search your TreeModel recursively and obtain a TreePath to the resulting node. Once you have the desired path, it’s easy to reveal it in the tree.

tree.setSelectionPath(path);
tree.scrollPathToVisible(path);

Addendum: Here’s one way to “obtain a TreePath.”

private TreePath find(DefaultMutableTreeNode root, String s) {
    @SuppressWarnings("unchecked")
    Enumeration<DefaultMutableTreeNode> e = root.depthFirstEnumeration();
    while (e.hasMoreElements()) {
        DefaultMutableTreeNode node = e.nextElement();
        if (node.toString().equalsIgnoreCase(s)) {
            return new TreePath(node.getPath());
        }
    }
    return null;
}

Leave a Comment