BCA

AJAVA LAB

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6

PART B

PROGRAM 7 PROGRAM 8 PROGRAM 9 PROGRAM 10 PROGRAM 11 PROGRAM 12 PROGRAM 13 PROGRAM 14 PROGRAM 15 . . .

 

 QUESTION :2. Write a java program to display the directory contents(subdirectories and files) in a tree format
using JTree class of swing.

FILE NAME : pro2.java
 
     import javax.swing.*; 
    import java.io.File; 
    import javax.swing.tree.DefaultMutableTreeNode;  
    public class pro2 {  
    JFrame f;  
    pro2(){  
        f=new JFrame();
  String maindirpath = "../";
  
        // File object
        File maindir = new File(maindirpath);
   if (maindir.exists() && maindir.isDirectory()) {
            File arr[] = maindir.listFiles();

           DefaultMutableTreeNode style=new DefaultMutableTreeNode(""+maindir);


 /// RECURSIVE FUNCTION CAll
            RecursiveAdd(arr, 0,style); 
 
        JTree jt=new JTree(style);  
        f.add(jt);  
        f.setSize(400,400);  
        f.setVisible(true); 
}

 
    }  
    public static void main(String[] args) {  
        new pro2();  


    }


static void RecursiveAdd(File[] arr, int level,DefaultMutableTreeNode style )
    {
        // for-each loop for main directory files
        for (File f : arr) {

            // tabs for internal levels
            for (int i = 0; i < level; i++)
                System.out.print("\t");
  
            if (f.isFile())
                {System.out.println(f.getName());
                 DefaultMutableTreeNode color=new DefaultMutableTreeNode(f.getName());
                    style.add(color);
             }
            else if (f.isDirectory())  
            {   System.out.println("[" + f.getName() + "]");
                 DefaultMutableTreeNode color=new DefaultMutableTreeNode(f.getName());
                    style.add(color);    
              
               
                // recursion for sub-directories
                RecursiveAdd(f.listFiles(), level + 1,color);
            }
        }
    } 


}