Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Component;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;

public class Main {
    static DefaultMutableTreeNode createTreeModel(File file, boolean recursive) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);
        if (file.isDirectory() && recursive) {
            File[] children = file.listFiles();
            if (children != null) {
                for (File f : children) {
                    node.add(createTreeModel(f, recursive));
                }
            }
        }
        return node;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame(Main.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTree tree = new JTree(createTreeModel(new File(System.getProperty("user.dir")), true));
        tree.setCellRenderer(new DefaultTreeCellRenderer() {
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                    boolean leaf, int row, boolean hasFocus) {
                super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
                if (value instanceof DefaultMutableTreeNode) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                    if (node.getUserObject() instanceof File) {
                        setText(((File) node.getUserObject()).getName());
                    }
                }
                return this;
            }
        });
        tree.getSelectionModel().addTreeSelectionListener(e -> {
            Object object = tree.getLastSelectedPathComponent();
            if (object instanceof DefaultMutableTreeNode) {
                Object userObject = ((DefaultMutableTreeNode) object).getUserObject();
                if (userObject instanceof File) {
                    File file = (File) userObject;
                    System.out.println(
                            "Selected file" + file.getAbsolutePath() + " Is directory? " + file.isDirectory());
                }
            }
        });
        JScrollPane pane = new JScrollPane(tree);
        frame.add(pane);
        frame.setSize(400, 600);
        frame.setVisible(true);
    }
}