Jtree expansion and selection problem

為{幸葍}努か 提交于 2020-01-06 08:33:33

问题


I have two JTrees instances (leftTree and rightTree). User can select some nodes from left tree and add the same to right tree. I have the below code in add button action listener to expand and select the node in rightTree after the node has been added.

rightTree.updateUI();

TreePath[] paths = leftTree.getSelectionPaths();
if (null != paths && paths.length > 0)
{
    TreePath path = paths[0];
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
    rightTree.scrollPathToVisible(new TreePath(node.getPath()));
    rightTree.setSelectionPaths(paths);
}

leftTree.clearSelection();

This code seems to work fine for some nodes but it cannot work for some other nodes in leftTree. The problem is even after the above code is executed, the rightTree is in collapsed state and I cannot see the selected node.

I have tried using other methods in JTree like setExpandsSelectedPaths(true), expandPath(new TreePath(node.getParent())). Also, tried calling rightTree.repaint() or rightTree.validate() after the above code is executed. But still the problem exists. But rightTree.isExpanded(new TreePath(node.getParent())) retruns true;

My tree is about 7-8 levels deep. Please help me to solve this and let me know if you need more information.


回答1:


For me the approach is incorrect. TreePath is in fact sequence of nodes from the current node to top most parent. In other words TreePath from node is created by calling getParet() till tull is reached. So if you get a node from one tree and create path the path is sequence of node in the original tree and the path is futile in the second tree because some nodes in the path just don't exists in the target tree model.

You need to get selected node and find an appropriate one in the second tree. Guess a node with the same user object. The for the found node in the target tree (if we found it) create TreePath and select/expand.



来源:https://stackoverflow.com/questions/5062864/jtree-expansion-and-selection-problem

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