简体   繁体   中英

Jtree expansion and selection problem

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM