java - 如何将子节点添加到最后一个父节点

标签 java nodes jtree

我想向最后一个父节点添加一些子节点,但这里我不使用变量来添加节点,这是我的代码以获取更多详细信息

代码:

Table table = new Table();
    XMLTable xtable = new XMLTable();

    File[] files = null; 
    File projectsDirectory = new File("projects");
    files = projectsDirectory.listFiles();
    for( File f : files){
        if(f.isDirectory()){
            root.add(new DefaultMutableTreeNode(f.getName()));// parent node added
            for(File fc : f.listFiles()){

                if(fc.isFile() && fc.getName().equalsIgnoreCase("table.xml")){

                    table = xtable.getXMLTable("table.xml");
                    ArrayList<Column> cols = table.getColumns();
                    for(Column col:cols){
                        ((DefaultMutableTreeNode) f.getName()).add(new DefaultMutableTreeNode(col.getName()));//don't work (just for test)
                    }

                }
            }

        }

最佳答案

add(...) 方法中内联创建 TreeNode 可能会搬起石头砸自己的脚,因为您最终没有可行的引用以供稍后在您的代码中使用。因此,不要在线创建树节点对象,而是在 for 循环中创建一个 TreeNode 变量,将对象分配给它,将其添加到根,然后使用局部变量添加更多节点,如果需要。

例如,

Table table = new Table();
XMLTable xtable = new XMLTable();

File[] files = null; 
File projectsDirectory = new File("projects");
files = projectsDirectory.listFiles();
for( File f : files){
    if(f.isDirectory()){
        TreeNode treeNode = new DefaultMutableTreeNode(f.getName());
        root.add(treeNode);// parent node added
        for(File fc : f.listFiles()){

            if(fc.isFile() && fc.getName().equalsIgnoreCase("table.xml")){

                table = xtable.getXMLTable("table.xml");
                ArrayList<Column> cols = table.getColumns();
                for(Column col:cols){
                    treeNode.add(new DefaultMutableTreeNode(col.getName()));
                }
            }
        }
    }
}

关于java - 如何将子节点添加到最后一个父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30794440/

相关文章:

java - 如何将 JList 对象放入 Java Swing 中的 Jtree 节点中?

java - Windows XP 上 IE7 和 IE8 的用户代理 - Java

javascript - 如何在 NodeJS 循环内处理多个 Google Places API 请求?

java - 在 Java 中实现和可视化二叉树

c - 为什么我的链表代码在删除头节点时会产生段错误?

java - 使用 Numbus L&F 设置 JTree 选择背景

java - JTree - 无法转换为 javax.swing.tree.MutableTreeNode

java - printf 模板的格式错误字符串问题

java - ActionBar setBackgroundDrawable强制关闭

java - 如何使用 webview 制作标签以从网址加载?