Java tutorial
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.io.File; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; public class MainClass extends JPanel { public MainClass(File dir) { setLayout(new BorderLayout()); JTree tree = new JTree(addNodes(null, dir)); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent(); System.out.println("You selected " + node); } }); JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); add(BorderLayout.CENTER, scrollpane); } DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) { String curPath = dir.getPath(); DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath); if (curTop != null) { curTop.add(curDir); } ArrayList ol = new ArrayList(); String[] tmp = dir.list(); for (int i = 0; i < tmp.length; i++) ol.add(tmp[i]); File f; ArrayList files = new ArrayList(); for (int i = 0; i < ol.size(); i++) { String thisObject = (String) ol.get(i); String newPath; if (curPath.equals(".")) newPath = thisObject; else newPath = curPath + File.separator + thisObject; if ((f = new File(newPath)).isDirectory()) addNodes(curDir, f); else files.add(thisObject); } for (int fnum = 0; fnum < files.size(); fnum++) curDir.add(new DefaultMutableTreeNode(files.get(fnum))); return curDir; } public Dimension getMinimumSize() { return new Dimension(200, 400); } public Dimension getPreferredSize() { return new Dimension(200, 400); } public static void main(String[] av) { JFrame frame = new JFrame("MainClass"); frame.setForeground(Color.black); frame.setBackground(Color.lightGray); Container cp = frame.getContentPane(); cp.add(new MainClass(new File("."))); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }