我想獲得一個桌面視圖中JTree
,是這樣的:桌面視圖僅適用於Windows
我有一個sample code這隻能說明了c:\
,因爲我是新到Java,找到實現它的困難。
這是到目前爲止我的代碼:
public class FileTreeDemo {
public static void main(String[] args) {
File root;
if (args.length > 0) {
root = new File(args[0]);
} else {
root = new File(System.getProperty("user.home"));
}
System.out.println(root);
FileTreeModel model = new FileTreeModel(root);
JTree tree = new JTree();
tree.setModel(model);
tree.setRootVisible(true);
tree.setShowsRootHandles(true);
JScrollPane scrollpane = new JScrollPane(tree);
JFrame frame = new JFrame("FileTreeDemo");
frame.getContentPane().add(scrollpane, "Center");
frame.setSize(400,600);
frame.setVisible(true);
}
}
FileTreeModel類
class FileTreeModel implements TreeModel {
protected File root;
public FileTreeModel(File root) { this.root = root; }
public Object getRoot() { return root; }
public boolean isLeaf(Object node) { return ((File)node).isFile(); }
public int getChildCount(Object parent) {
String[] children = ((File)parent).list();
if (children == null) return 0;
return children.length;
}
public Object getChild(Object parent, int index) {
String[] children = ((File)parent).list();
if ((children == null) || (index >= children.length)) return null;
return new File((File) parent, children[index]);
}
public int getIndexOfChild(Object parent, Object child) {
String[] children = ((File)parent).list();
if (children == null) return -1;
String childname = ((File)child).getName();
for(int i = 0; i < children.length; i++) {
if (childname.equals(children[i])) return i;
}
return -1;
}
public void valueForPathChanged(TreePath path, Object newvalue) {}
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
}
到目前爲止,我已經試圖改變 '系統屬性',但沒有奏效:
"user.dir"
請給我看一些指示,謝謝。
另請參閱[文件瀏覽器GUI](http://codereview.stackexchange.com/q/4446/7784)。 – 2014-12-06 00:49:31