【问题标题】:Update selectionPaths in a JTree when the model updates模型更新时更新 JTree 中的 selectionPaths
【发布时间】:2012-06-05 20:07:39
【问题描述】:

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

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

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

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java swing jtree


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您能够找到叶子的新路径,您可以创建一个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;
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-19
      • 2012-06-22
      • 2011-03-28
      • 1970-01-01
      • 2011-04-18
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      相关资源
      最近更新 更多