import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
public class JTreeFileChooserExample extends JFrame {
private JFileTree t = new JFileTree();
private JLabel l = new JLabel(" ");
public JTreeFileChooserExample() {
super("JTree FileChooser Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setAlwaysOnTop(true);
this.setLocationByPlatform(true);
this.setSize(480, 320);
t.getSelectionModel().addTreeSelectionListener(
new TreeSelectionListener() {
private File file;
private File[] files;
private DefaultMutableTreeNode dmt;
private Object[] o;
private String s = "";
public void valueChanged(TreeSelectionEvent e) {
dmt = null;
dmt = (DefaultMutableTreeNode) e
.getNewLeadSelectionPath()
.getLastPathComponent();
o = dmt.getUserObjectPath();
s = "";
for (Object ob : o) {
s = s + ob;
}
file = new File(s);
l.setText(file.getAbsolutePath());
if (file.isDirectory())
if ((files = file.listFiles()).length > 0) {
dmt.removeAllChildren();
for (int ast = 0; ast < files.length; ast++) {
if (files[ast].isDirectory())
dmt.add(new DefaultMutableTreeNode(
files[ast].getName() + "\\"));
else
dmt.add(new DefaultMutableTreeNode(
files[ast].getName()));
}
t.validate();
}
}
});
this.add(new JScrollPane(t), BorderLayout.CENTER);
this.add(l, BorderLayout.SOUTH);
this.setVisible(true);
}
public static void main(String[] args) {
new JTreeFileChooserExample();
}
class JFileTree extends JTree {
public JFileTree() {
this.setModel(new DefaultTreeModel(this.getRoot()));
this.setCellRenderer(new FileRenderer());
}
public DefaultMutableTreeNode getRoot() {
File f = new File("C:\\");
File[] files = f.listFiles();
DefaultMutableTreeNode root = new DefaultMutableTreeNode(f
.getPath());
for (int ast = 0; ast < files.length; ast++) {
if (files[ast].isDirectory())
root.add(new DefaultMutableTreeNode(files[ast].getName()
+ "\\"));
else
root.add(new DefaultMutableTreeNode(files[ast].getName()));
}
return root;
}
class FileRenderer extends DefaultTreeCellRenderer {
private Icon directoryIcon;
public FileRenderer() {
directoryIcon = this.getDefaultClosedIcon();
}
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 (isDirectory(value))
setIcon(directoryIcon);
return this;
}
private Object[] o;
private String s;
private File file;
protected boolean isDirectory(Object value) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
o = node.getUserObjectPath();
s = "";
for (Object ob : o) {
s = s + ob;
}
file = new File(s);
if (file.isDirectory())
return true;
else
return false;
}
}
}
}