您如何将一个节点插入树路径中的另一个节点?

时间:2019-01-10 01:31:36

标签: java swing

在Java Swing中,我有两个节点和一个TreePath。 一个节点包含“根”节点(我们称其为nodeA),它包含其下的所有内容。  第二个节点是“新”节点(我们称其为nodeB),它包含一个新节点。 我有一个TreePath,显示我要在nodeA中插入nodeB的位置。我正在尝试开发一个功能来做到这一点。有什么帮助吗? 预先感谢!

Node A   
 ~
      Documents
         -- text1.txt
         -- text2.txt
      Pictures
         - text1.txt

我想将下面的节点插入“图片”文件夹

folder1
   -- newtext1.txt

我的insertNodes函数:

private static void insertNodes
        (DefaultMutableTreeNode root
            ,DefaultMutableTreeNode newNode
                ,String tp)
{
    String[] elements = tp.split("/");
    String treePath = "";
    for (int i=0; i<elements.length-1; i++)
    {
        if (i == elements.length-2)
        {
            treePath += elements[i];
        } else {
        treePath += elements[i] + "/" ;
        }
    }
    System.out.println("TreePath : " + treePath);

    DefaultMutableTreeNode node = buildNodeFromString(treePath);
    DefaultMutableTreeNode lastLeaf = node.getLastLeaf();
    TreePath path = new TreePath(lastLeaf.getPath());
    System.out.println("insertNodes-Path =" + path);
    DefaultTreeModel model = new DefaultTreeModel(root);



    DefaultMutableTreeNode pictureNode = (DefaultMutableTreeNode) path.getLastPathComponent();
    pictureNode.add(newNode);





    // Notify the model of the changes
    model.nodesWereInserted(pictureNode, new int[]{pictureNode.getChildCount() - 1});

    // The above way (you suggested) wipes out everything and just puts one "~" in the JTree


    // The below line adds them all to the "~" direcotry
    //root.add(newNode); 


}

我的getFileStructure(在这里我称为insertNodes)

    public static DefaultMutableTreeNode getFileStructure(FTPClient client,String workingPath,DefaultMutableTreeNode style )
{

try {
    System.out.println("\n");
    System.out.println("Working Path: " + workingPath);
    FTPFile[] files = client.listFiles(workingPath);
    DefaultMutableTreeNode node = buildNodeFromString(workingPath);
    DefaultMutableTreeNode lastLeaf = node.getLastLeaf();
    TreePath path = new TreePath(lastLeaf.getPath());
    System.out.println("Path =" + path);
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)(path.getLastPathComponent());       
    System.out.println("Add to Node:" + selectedNode.toString());
    for (FTPFile file : files) {
        if (file.isDirectory())
        {
            // DefaultMutableTreeNode fileDirectory =new DefaultMutableTreeNode(file.getName());
            // selectedNode.add(fileDirectory);

            System.out.println("\t Folder Name: " + file.getName());
            getFileStructure(client, workingPath + "/" + file.getName(),style);
        } else {
        DefaultMutableTreeNode root =new DefaultMutableTreeNode();  
        System.out.println("Filename: " + file.getName());

        DefaultMutableTreeNode fileDirectory =new DefaultMutableTreeNode(file.getName());


        selectedNode.add(fileDirectory);

        System.out.println("Added to node = " + selectedNode.toString());
        System.out.println("First Node = " + selectedNode.getFirstChild().toString());
        System.out.println("Last Node = " + selectedNode.getLastChild().toString());
        System.out.println("Num of Children = " + selectedNode.getLeafCount());
        System.out.println("Depth Count= " + selectedNode.getDepth());
        }
    }
    insertNodes(style,selectedNode,workingPath);        
} catch (IOException ex) {
    System.out.println("IOException:" + ex);
 } 



 return style;
}

1 个答案:

答案 0 :(得分:1)

好的,假设一些,假设您有一个TreeModel,看起来像这样……

DefaultMutableTreeNode root = new DefaultMutableTreeNode("~");
DefaultTreeModel model = new DefaultTreeModel(root);

DefaultMutableTreeNode docs = new DefaultMutableTreeNode("Documents");
docs.add(new DefaultMutableTreeNode("text1.txt"));
docs.add(new DefaultMutableTreeNode("text2.txt"));
root.add(docs);

DefaultMutableTreeNode pics = new DefaultMutableTreeNode("Pictures");
pics.add(new DefaultMutableTreeNode("text1.txt"));
root.add(pics);

这将生成一棵看起来像...的树

+ ~
  + Documents
    - text1.txt
    - text2.txt
  + Pictures
    - text1.txt

然后,假设您知道要添加...

DefaultMutableTreeNode newFolder = new DefaultMutableTreeNode("folder1");
newFolder.add(new DefaultMutableTreeNode("text1.txt"));

~/Pictures

假设您在TreePath上有一个有效的[~, Pictures],则可以简单地从路径中获取lastComponent,该路径将引用Pictures {{1} },那么您可以简单地做类似...

TreeNode

这将生成像...的树

DefaultMutableTreeNode pictureNode = (DefaultMutableTreeNode) treePathFromPicturesToRoot.getLastPathComponent();
pictureNode.add(newFolder);

// Notify the model of the changes
model.nodesWereInserted(pictureNode, new int[]{pictureNode.getChildCount() - 1});

现在,我不知道您+ ~ + Documents - text1.txt - text2.txt + Pictures - text1.txt + folder1 - text1.txt 的来源,但我认为这是由TreePath中实际存在的节点组成的有效路径,否则它将无法正常工作很好

现在,基于许多示例,如果这不能满足您的需求,那么您将需要提供Minimal, Complete, and Verifiable example,以便我们更好地了解您的问题

示例代码...

我使用以下代码构建了基本概念

TreeModel

已根据其他代码进行了更新...

您的插入方法应该和...一样简单

import java.util.Enumeration;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class Test {

    public static void main(String[] args) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("~");
        DefaultTreeModel model = new DefaultTreeModel(root);

        DefaultMutableTreeNode docs = new DefaultMutableTreeNode("Documents");
        docs.add(new DefaultMutableTreeNode("text1.txt"));
        docs.add(new DefaultMutableTreeNode("text2.txt"));
        root.add(docs);

        DefaultMutableTreeNode pics = new DefaultMutableTreeNode("Pictures");
        pics.add(new DefaultMutableTreeNode("text1.txt"));
        root.add(pics);

        describe(model);

        DefaultMutableTreeNode newFolder = new DefaultMutableTreeNode("folder1");
        newFolder.add(new DefaultMutableTreeNode("text1.txt"));

        TreeNode[] pathToRoot = pics.getPath();
        TreePath treePathFromPicturesToRoot = new TreePath(pathToRoot);
        System.out.println(treePathFromPicturesToRoot);

        DefaultMutableTreeNode pictureNode = (DefaultMutableTreeNode) treePathFromPicturesToRoot.getLastPathComponent();
        pictureNode.add(newFolder);

        model.nodesWereInserted(pictureNode, new int[]{pictureNode.getChildCount() - 1});

        describe(model);
    }

    protected static void describe(DefaultTreeModel model) {
        describe((DefaultMutableTreeNode) model.getRoot(), 0);
    }

    protected static void describe(DefaultMutableTreeNode node, int level) {
        StringBuilder padding = new StringBuilder();
        for (int index = 0; index < level; index++) {
            padding.append("  ");
        }
        System.out.println(padding + "+ " + node);
        padding.append("  ");
        Enumeration<TreeNode> children = node.children();
        while (children.hasMoreElements()) {
            DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) children.nextElement();
            if (childNode.isLeaf()) {
                System.out.println(padding + "- " + childNode);
            } else {
                describe(childNode, level + 1);
            }
        }
    }
}

要基于private static void insertNodes( DefaultTreeModel model, DefaultMutableTreeNode parent, DefaultMutableTreeNode newNode) { parent.add(newNode); model.nodesWereInserted(parent, new int[]{parent.getChildCount() - 1}); } 路径查找节点,您可以“执行” ...

String

这意味着,根据我之前的示例,您可以执行以下操作...

protected static DefaultMutableTreeNode findNode(DefaultTreeModel model, String path) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) model.getRoot();
    String[] parts = path.split("/");
    if (node.getUserObject().toString().equals(parts[0])) {
         return findNode(node, Arrays.copyOfRange(parts, 1, parts.length));
    }
    return null;
}

protected static DefaultMutableTreeNode findNode(DefaultMutableTreeNode node, String[] path) {
    if (path.length == 0) {
        return node;
    }
    Enumeration<TreeNode> children = node.children();
    while (children.hasMoreElements()) {
        DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement();
        if (child.getUserObject().toString().equals(path[0])) {
            return findNode(node, Arrays.copyOfRange(path, 1, path.length));
        }
    }
    return null;
}

示例2

DefaultMutableTreeNode newFolder = new DefaultMutableTreeNode("folder1");
newFolder.add(new DefaultMutableTreeNode("text1.txt"));

insertNodes(model, findNode(model, "~/Pictures"), newFolder);