简体   繁体   English

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

[英]Get selected filename and path from JTree

Trying to get selected filename with path from the JTree - TreeSelectionListener, I got stuck on this! 试图从JTree-TreeSelectionListener中获取带有路径的选定文件名,我陷入了困境! Please give me direction to get the filename with path, have copied the complete code so far I tried. 请给我指导,以获取带有路径的文件名,到目前为止,我已经复制了完整的代码。

EDIT:1 编辑: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);
            }
        });
    }
}

Getting the value from the object filePathToAdd like 从对象filePathToAdd获取值

You selected viewgui.FileTreePanel$FileTreeNode@68556f62

Edit:2 编辑:2

Expected output -> G:\\java_code\\Temp\\tempfile.txt 预期输出-> G:\\ java_code \\ Temp \\ tempfile.txt

Trying to loop thro' to get value but wasn't successful! 试图循环获得价值,但没有成功! please give me directions, Thx 请给我指示,Thx

The first thing you need to do, is update FileTreeNode to provide a getter to return the File which this node represents... 您需要做的第一件事是更新FileTreeNode以提供一个getter来返回该节点代表的File ...

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

    public File getFile() {
        return file;
    }

Next, in your TreeSelectionListener , you need to get the selectionPath , get the lastPathComponent , test to see if it is a FileTreeNode and get the File it represents, for example... 接下来,在TreeSelectionListener ,您需要获取selectionPath ,获取lastPathComponent ,进行测试以查看其是否为FileTreeNode并获取其表示的File ,例如。

tree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
        TreePath tp = tree.getSelectionPath();
        if (tp != null) {
            Object filePathToAdd = tp.getLastPathComponent();
            System.out.println(filePathToAdd);
            if (filePathToAdd instanceof FileTreeNode) {
                FileTreeNode node = (FileTreeNode) filePathToAdd;
                File file = node.getFile();
                System.out.println(file);
            }
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM