2012-06-05 44 views
0

我有一个带有自定义对象和自定义模型的JTree。 在某些时候,我选择了一个节点,当发生这种情况时,我使用新的检索数据更新树。 当发生这种情况时,我会通过树找到选定的节点并用新的节点替换它(最新)。 当我找到它时,我将旧节点从其父节点中删除,在其位置中添加新节点并调用nodeChanged(newNode)。树更新正常,新节点出现更新的内容。在模型更新时更新JTree中的选择路径

问题是,当从这个树更新回来时,选择路径没有被更新,所以当我使用方法getSelectionPaths()时,返回路径(如果只有一个节点被选中)对应于旧节点I从树上移除。

如何更新到新更新模型的选择路径?

+1

为了更好地帮助越早,张贴[SSCCE](http://sscce.org/)。 –

回答

3

您可以创建一个新的TreePath并用新路径调用setSelectedPath。但是,更好的办法是,不要删除节点,而是使其变为可变并更新节点。这样树模型不会改变,选择路径也不会改变。

您还需要触发相应的事件(节点已更改,而不是节点已删除/添加等)。

0

如果你能够找到你的叶的新路径,你可以创建一个TreePath

我提出的例子,选择在JTree叶具有节点的一层:

public JTree    fileTree; 
public void setJTreePath(String leafName, String nodeName) { 

    TreeNode root = (TreeNode) fileTree.getModel().getRoot(); 
    TreePath path = new TreePath(root); 
    int rootChildCount = root.getChildCount(); 
    mainLoop: 
    for (int i = 0; i < rootChildCount; i++) { 

     TreeNode child = root.getChildAt(i); 
     if (child.toString().equals(nodeName)) { 
      path = path.pathByAddingChild(child); 
      int ChildCount = child.getChildCount(); 
      for (int j = 0; j < ChildCount; j++) { 
       TreeNode child2 = child.getChildAt(j); 
       if (child2.toString().equals(leafName)) { 
        path = path.pathByAddingChild(child2); 
        fileTree.setSelectionPath(path); 

        //I've used a SwingUtilities here, maybe it's not mandatory 
        SwingUtilities.invokeLater(
          new Runnable() { 
           @Override 
           public void run() { 
            fileTree.scrollPathToVisible(fileTree.getSelectionPath()); 
           } 
          }); 
        break mainLoop; 
       } 
      } 
     } 
    } 
}