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