3

I have a JTree (myTree) and in another class, I have a DefaultMutableTreeNode which was taken from myTree.

In a certain function, I want the JTree to highlight the node.

I tried:

myTree.setSelectionPath(new TreePath(treeNode));

but visually nothing is happening.

any ideas?

UPDATE:

I have also another JTable which is rendered based on the selected treeNode in myTree. The table is updating correctly. It's just the myTree which refused to update visually.

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
  • Is the tree focused at the time the function is called? I would not need to ask if you'd posted an [SSCCE](http://sscce.org/). – Andrew Thompson Jan 17 '12 at 15:01
  • @AndrewThompson No, Actually the focus is in another JTree. Sorry I cannot post more code because it is highly confidential. I don't know if I am permitted to post a question here :P – Adel Boutros Jan 17 '12 at 15:05

3 Answers3

4

You need to use the actual tree path of the node. Not just an instance of TreePath:

myTree.setSelectionPath(new TreePath(treeModel.getPathToRoot(treeNode)));

Also, the javadoc says:

If any component of the path is hidden (under a collapsed node), and getExpandsSelectedPaths is true it is exposed (made viewable)

So make sure that getExpandsSelectedPaths is true.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
4

From the java API, we get the description of TreePath below:

Represents a path to a node. A TreePath is an array of Objects that are vended from a TreeModel. The elements of the array are ordered such that the root is always the first element (index 0) of the array.

so, a valid TreePath must be constructed from an array including all nodes on the path from the root node and the node you want to select.

Alanmars
  • 1,267
  • 1
  • 11
  • 21
0

Many Swing bugs, quirks and other shortcomings can be worked around using SwingUtilities.invokeLater(Runnable):

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        // JB Nizet's solution:
        myTree.setSelectionPath(new TreePath(treeModel.getPathToRoot(treeNode)));
    }
});

This also solves the same problem with JTree.setSelectionPaths(TreePath[]).

Steve
  • 8,066
  • 11
  • 70
  • 112