highlight the treeNode in the Jtree using the treeNode itself

六月ゝ 毕业季﹏ 提交于 2019-12-23 20:24:16

问题


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



来源:https://stackoverflow.com/questions/8896678/highlight-the-treenode-in-the-jtree-using-the-treenode-itself

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!