Practical 7
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class p71 {
public static void main(String[] args) {
DefaultMutableTreeNode root = new
DefaultMutableTreeNode("India");
DefaultMutableTreeNode maharashtra = new
DefaultMutableTreeNode("Maharashtra");
DefaultMutableTreeNode gujarat = new
DefaultMutableTreeNode("Gujarat");
root.add(maharashtra);
root.add(gujarat);
DefaultMutableTreeNode mumbai = new
DefaultMutableTreeNode("Mumbai");
DefaultMutableTreeNode pune = new
DefaultMutableTreeNode("Pune");
DefaultMutableTreeNode nashik = new
DefaultMutableTreeNode("Nashik");
DefaultMutableTreeNode nagpur = new
DefaultMutableTreeNode("Nagpur");
maharashtra.add(mumbai);
maharashtra.add(pune);
maharashtra.add(nashik);
maharashtra.add(nagpur);
JTree tree = new JTree(root);
JFrame frame = new JFrame("JTree Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new JScrollPane(tree));
frame.setVisible(true);
OUTPUT:
import java.io.File;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class FileTree {
private JFrame frame;
private JTree tree;
public FileTree(String rootPath) {
DefaultMutableTreeNode root = new DefaultMutableTreeNode(new
File(rootPath));
DefaultTreeModel treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
createNodes(root, new File(rootPath));
frame = new JFrame("File System Viewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.add(new JScrollPane(tree));
frame.setVisible(true);
private void createNodes(DefaultMutableTreeNode node, File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
DefaultMutableTreeNode childNode = new
DefaultMutableTreeNode(f);
node.add(childNode);
createNodes(childNode, f);
public static void main(String[] args) {
new FileTree("/");
OUTPUT: