How to add children nodes to the last parent node

94 views Asked by At

i wanna add some children nodes to the last parent node but here I don't work with variables to add nodes and this is my code for more details

Code :

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)
                    }

                }
            }

        }
1

There are 1 answers

0
Hovercraft Full Of Eels On BEST ANSWER

You may be shooting yourself in the foot by creating your TreeNodes inline, within the add(...) method, since you end up with no viable reference to use later in your code. So instead, don't create your tree node objects in-line, but instead, within your for loop, create a TreeNode variable, assign it the object, add it to the root, and then use the local variable to add more nodes if need be.

e.g.,

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()));
                }
            }
        }
    }
}