从JTree获取选定的文件名和路径

时间:2015-12-14 15:19:56

标签: java swing file path

尝试使用JTree - TreeSelectionListener中的路径获取所选文件名,我对此感到困惑!请给我指示路径获取文件名,到目前为止我已经复制了完整的代码。

编辑:1

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.util.*;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
public class FileTreePanel extends JPanel {
    /**
     * File system view.
     */
    protected static FileSystemView fsv = FileSystemView.getFileSystemView();

    /**
     * Renderer for the file tree.
     * 
     */
    private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {
        /**
         * Icon cache to speed the rendering.
         */
        private Map<String, Icon> iconCache = new HashMap<String, Icon>();

        /**
         * Root name cache to speed the rendering.
         */
        private Map<File, String> rootNameCache = new HashMap<File, String>();

        /*
         * (non-Javadoc)
         * 
         * @see javax.swing.tree.DefaultTreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree,
         *      java.lang.Object, boolean, boolean, boolean, int, boolean)
         */
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean sel, boolean expanded, boolean leaf, int row,
                boolean hasFocus) {
            FileTreeNode ftn = (FileTreeNode) value;
            File file = ftn.file;
            String filename = "";
            if (file != null) {
                if (ftn.isFileSystemRoot) {
                    filename = this.rootNameCache.get(file);
                    if (filename == null) {
                        filename = fsv.getSystemDisplayName(file);
                        this.rootNameCache.put(file, filename);
                    }
                } else {
                    filename = file.getName();
                }
            }
            JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,
                    filename, sel, expanded, leaf, row, hasFocus);
            if (file != null) {
                Icon icon = this.iconCache.get(filename);
                if (icon == null) {
                    icon = fsv.getSystemIcon(file);
                    this.iconCache.put(filename, icon);
                }
                result.setIcon(icon);
            }
            return result;
        }
    }

    /**
     * A node in the file tree.
     * 
     */
    private static class FileTreeNode implements TreeNode {
        /**
         * Node file.
         */
        private File file;

        /**
         * Children of the node file.
         */
        private File[] children;

        /**
         * Parent node.
         */
        private TreeNode parent;

        /**
         * Indication whether this node corresponds to a file system root.
         */
        private boolean isFileSystemRoot;

        /**
         * Creates a new file tree node.
         * 
         * @param file
         *            Node file
         * @param isFileSystemRoot
         *            Indicates whether the file is a file system root.
         * @param parent
         *            Parent node.
         */
        public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent) {
            this.file = file;
            this.isFileSystemRoot = isFileSystemRoot;
            this.parent = parent;
            this.children = this.file.listFiles();
            if (this.children == null)
                this.children = new File[0];
                //System.out.println(children);
        }

        /**
         * Creates a new file tree node.
         * 
         * @param children
         *            Children files.
         */
        public FileTreeNode(File[] children) {
            this.file = null;
            this.parent = null;
            this.children = children;
        }

        public Enumeration<?> children() {
            final int elementCount = this.children.length;
            return new Enumeration<File>() {
                int count = 0;

                public boolean hasMoreElements() {
                    return this.count < elementCount;
                }

                public File nextElement() {
                    if (this.count < elementCount) {
                        return FileTreeNode.this.children[this.count++];
                    }
                    throw new NoSuchElementException("Vector Enumeration");
                }
            };

        }

        public boolean getAllowsChildren() {
            return true;
        }

        public TreeNode getChildAt(int childIndex) {
            return new FileTreeNode(this.children[childIndex],
                    this.parent == null, this);
        }

        public int getChildCount() {
            return this.children.length;
        }

        public int getIndex(TreeNode node) {
            FileTreeNode ftn = (FileTreeNode) node;
            for (int i = 0; i < this.children.length; i++) {
                if (ftn.file.equals(this.children[i]))
                    return i;
            }
            return -1;
        }

        public TreeNode getParent() {
            return this.parent;
        }

        public boolean isLeaf() {
            return (this.getChildCount() == 0);
        }
    }

    /**
     * The file tree.
     */
    private JTree tree;

    /**
     * Creates the file tree panel.
     */
    public FileTreePanel() {
        //@trashgod's hint
        this.setLayout(new BorderLayout());
        //
        File[] roots = File.listRoots();
        FileTreeNode rootTreeNode = new FileTreeNode(roots);
        this.tree = new JTree(rootTreeNode);
        this.tree.setCellRenderer(new FileTreeCellRenderer());
        this.tree.setRootVisible(false);
        final JScrollPane jsp = new JScrollPane(this.tree);

        tree.setVisibleRowCount(15);

        Dimension preferredSize = jsp.getPreferredSize();
        Dimension widePreferred = new Dimension(300,(int)preferredSize.getHeight());
        jsp.setPreferredSize( widePreferred );

        jsp.setBorder(new EmptyBorder(0, 0, 50, 0));
        this.add(jsp, BorderLayout.WEST);

        this.tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        this.tree.setShowsRootHandles(true);

        tree.addTreeSelectionListener(new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                TreePath tp = tree.getLeadSelectionPath();
                if (tp!= null){
                    // Trying to get selected filename with path
                    Object filePathToAdd = tp.getPath()[tp.getPathCount()-1];
                    String objToStr = filePathToAdd.toString();

                    System.out.println("You selected " + filePathToAdd );

                    //http://stackoverflow.com/questions/4123299/how-to-get-datas-from-listobject-java
                    /*List<Object> list = (List<Object>) filePathToAdd;
                    for (int i=0; i<list.size(); i++){
                       Object[] row = (Object[]) list.get(i);
                       System.out.println("Element "+i+Arrays.toString(row));
                    }*/
                }

              }
            });

        JLabel lblNewLabel = new JLabel("Version 0.1.0   ");
        lblNewLabel.setForeground(Color.GRAY);
        lblNewLabel.setFont(new Font("Calibri", Font.BOLD, 12));
        lblNewLabel.setBorder(new EmptyBorder(-740, 0, 0, 0));
        this.add(lblNewLabel, BorderLayout.EAST);
    }

/**
 * @author Kirill Grouchnikov @http://www.pushing-pixels.org/
 */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Student Record Book");
                frame.setSize(1200, 800);
                frame.setLocationRelativeTo(null);
                frame.add(new FileTreePanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

从对象 filePathToAdd 获取值

You selected viewgui.FileTreePanel$FileTreeNode@68556f62

编辑:2

预期输出 - &gt; G:\ java_code \ TEMP \ tempfile.txt

试图循环thro'以获得价值,但没有成功!请给我指示,Thx

1 个答案:

答案 0 :(得分:2)

您需要做的第一件事就是更新FileTreeNode以提供getter来返回此节点所代表的File ...

private static class FileTreeNode implements TreeNode {
    //...

    public File getFile() {
        return file;
    }

接下来,在您的TreeSelectionListener中,您需要获取selectionPath,获取lastPathComponent,测试一下是FileTreeNode并获取{{1}它表示,例如......

File