请问各位大虾,我想把系统里面的本地磁盘列到JTree里面,就像有些软件选择目录(文件夹)的窗口一样,可以进行对本地磁盘的查询,提取在本地磁盘上面选择的目录文件夹,请问这个应该怎么实现呢?希望各位帮帮忙,最好附源码,谢谢!

解决方案 »

  1.   

    import java.io.File;
    import java.util.*;import javax.swing.filechooser.FileSystemView;
    import javax.swing.tree.TreeNode;public class DirTreeNode implements TreeNode {
    private File dir = null; private List<DirTreeNode> children = null; private DirTreeNode parent;

    public DirTreeNode(File dir, DirTreeNode parent) {
    this.dir = dir;
    this.parent = parent;
    } public TreeNode getChildAt(int childIndex) {
    initChildrenList(); return (TreeNode) children.get(childIndex);
    } public int getChildCount() {
    initChildrenList();

    return children.size();
    } public TreeNode getParent() {
    return parent;
    } public int getIndex(TreeNode node) {
    initChildrenList(); return children.indexOf(node);
    } public boolean getAllowsChildren() {
    return true;
    } public boolean isLeaf() {
    if (dir != null && FileSystemView.getFileSystemView().isFloppyDrive(dir)) {
    return false;
    } initChildrenList(); return children.isEmpty();
    } public Enumeration children() {
    initChildrenList(); final Iterator iter = children.iterator();
    return new Enumeration() {
    public boolean hasMoreElements() {
    return iter.hasNext();
    } public Object nextElement() {
    return iter.next();
    }
    };
    } private void initChildrenList() {
    if (children == null) {
    File[] subDirs = null;
    if (dir == null) {
    subDirs = FileSystemView.getFileSystemView().getRoots();
    }
    else {
    subDirs = FileSystemView.getFileSystemView().getFiles(dir, false);
    }
    if (subDirs == null || subDirs.length == 0) {
    children = Collections.emptyList();
    }
    else {
    children = new ArrayList<DirTreeNode>();
    for (int i = 0; i < subDirs.length; i++) {
    if (subDirs[i]!= null && subDirs[i].isDirectory()) {
    children.add(new DirTreeNode(subDirs[i], this));
    }
    }
    }
    }
    } public File getDir() {
    return dir;
    } public String toString() {
    return dir == null ? 
    "" : FileSystemView.getFileSystemView().getSystemDisplayName(dir);
    } public boolean equals(Object obj) {
    if (obj instanceof DirTreeNode) {
    DirTreeNode t = (DirTreeNode) obj;
    return dir == null ? t.dir == null : dir.equals(t.dir);
    }
    return false;
    } public int hashCode() {
    return dir == null ? 0 : dir.hashCode();
    }}
      

  2.   


    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;import javax.swing.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.filechooser.FileSystemView;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreePath;public class DirChooserDialog
    extends JDialog
    {
    private JLabel descrLabel = new JLabel("", JLabel.LEFT);
    private JTree dirTree = null;
    private JScrollPane scrollPane = null;

    private JButton okBtn = new JButton("确定");
    private JButton cancleBtn = new JButton("取消");

    private JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    private boolean okBtnPressed;

    public DirChooserDialog(Frame owner, String dialogTitle, String descrStr) {
    super(owner, dialogTitle, true); initComponents(descrStr);
    } public DirChooserDialog(Dialog owner, String dialogTitle, String descrStr) {
    super(owner, dialogTitle, true);

    initComponents(descrStr);
    } private void initComponents(String descrStr)
    {
    descrLabel.setText(descrStr); btnPanel.add(okBtn);
    btnPanel.add(cancleBtn);

    DirTreeNode rootNode = new DirTreeNode(null, null);
    dirTree = new JTree(rootNode);
    dirTree.setCellRenderer(new DefaultTreeCellRenderer() {
    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);

    DirTreeNode node = (DirTreeNode) value;
    if (node.getDir() != null) {
    setIcon(FileSystemView.getFileSystemView().getSystemIcon(node.getDir()));
    }
    return this;
    }
    });
    dirTree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e)
    {
    updateOKBtnState();
    }
    });
    dirTree.setRootVisible(false);
    dirTree.expandRow(0);
    JScrollPane scrollPane = new JScrollPane(dirTree);
    scrollPane.setPreferredSize(new Dimension(300, 300));

    okBtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
    okBtnPressed = true;
    dispose();
    }
    });

    cancleBtn.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    okBtnPressed = false;
    dispose();
    }
    });

    ((JComponent) getContentPane()).setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
    getContentPane().setLayout(new BorderLayout(5, 5)); getContentPane().add(descrLabel, BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(btnPanel, BorderLayout.SOUTH);

    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    updateOKBtnState();
    pack();
    } private void updateOKBtnState()
    {
    okBtn.setEnabled(getSelectedDir() != null);
    } public File showDirChooserDialog() {
    okBtnPressed = false;

    Rectangle bounds = getParent().getBounds();
    setLocation(bounds.x + (bounds.width - getWidth()) / 2 ,
            bounds.y + (bounds.height - getHeight()) / 2);
    setVisible(true); if (okBtnPressed) {
    return getSelectedDir();
    }
    else {
    return null;
    }
    }

    public File getSelectedDir() {
    TreePath path = dirTree.getSelectionPath();
    if (path == null || path.getPathCount() == 1) {
    return null;
    }
    DirTreeNode node = (DirTreeNode) path.getLastPathComponent(); return node.getDir();
    }

    public void setSelectedDir(File dir) {
    List<File> pathList = new LinkedList<File>();
    do {
    pathList.add(0, dir);
    dir = dir.getParentFile();
    } while (dir != null);

    TreePath path = new TreePath(dirTree.getModel().getRoot());
    for (Iterator iter = pathList.iterator(); iter.hasNext();) {
    File d = (File) iter.next();
    path = path.pathByAddingChild(
    new DirTreeNode(d, (DirTreeNode) path.getLastPathComponent()));
    }

    dirTree.setSelectionPath(path);
    dirTree.scrollPathToVisible(path);
    }

    public static void main(String[] args)
    {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
    e.printStackTrace();
    } final JFrame f = new JFrame("DirChooserTest"); JButton btn = new JButton("ChooseDir");
    btn.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    DirChooserDialog dlg = new DirChooserDialog(f, "DirChooserDialog", "选择保存文件的目录:");
    //dlg.setSelectedDir(new File("F:/temp"));
    System.out.println(dlg.showDirChooserDialog());
    }
    }); f.getContentPane().add(btn, BorderLayout.CENTER);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }
    }
      

  3.   

    非常感谢,不过我有个地方没有搞明白,就是像
    List<File> pathList = new LinkedList<File>();这样的语句,为什么用<>这个符号?我告白明白,编译器也报错,不知道是什么问题?
      

  4.   

    这是1.5里面新加的语法,如果你用1.4的话就把所有的<>都删掉,然后有些地方需要加上强制类型转换
      

  5.   

    谢谢你,我使用的1.5的JVM通过了编译,但是你能不能讲一下,<>的作用,什么时候用,是做什么用的可以吗?
      

  6.   

    http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf