下面打算以树结构显示文件目录:
先来个热身吧,先实现下面的图像再说,回忆一下Jtree的用法。其实主要是我对swing不熟悉,哈哈。
代码如下:
package File;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
public class TreeSimple extends JFrame{
public TreeSimple(){
JPanel panel = new JPanel();
JTextArea area = new JTextArea(5, 30);
JTree tree = new JTree();
JScrollPane js1 = new JScrollPane(tree,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
panel.setLayout(new FlowLayout());
JScrollPane js = new JScrollPane(area);
JSplitPane jsplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,
js1, js);
panel.add(jsplit);
setContentPane(panel);
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new TreeSimple();
}
}
下面才是正式的
运行结果如下:
package File;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
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;
import javax.swing.tree.TreePath;
public class Disktree extends JFrame implements TreeSelectionListener{
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
JTree tree = new JTree(rootNode);
JPanel panel = new JPanel();
public Disktree(){
tree.addTreeSelectionListener(this);
JScrollPane js = new JScrollPane(tree,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
panel.add(tree);
setContentPane(panel);
addWindowListener(new WindowAdapter(){
@Override
public void windowActivated(WindowEvent e){
File[] files = File.listRoots();
for(File file : files){
DefaultMutableTreeNode node = new DefaultMutableTreeNode(
file);
rootNode.add(node);
}
tree.expandPath(new TreePath(rootNode));
}
});
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new Disktree();
}
@Override
public void valueChanged(TreeSelectionEvent e){
TreePath path = e.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
.getLastPathComponent();
Object userObject = node.getUserObject();
if(!(userObject instanceof File)){
return;
}
File folder = (File) userObject;
if(!folder.isDirectory()){
return;
}
File[] files = folder.listFiles();
for(File file : files){
node.add(new DefaultMutableTreeNode(file));
}
}
}