highlight the treeNode in the Jtree using the tree

2019-07-04 18:15发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

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[]).



标签: java swing jtree