从JTree获取选定的文件名和路径 [英] Get selected filename and path from JTree

查看:102
本文介绍了从JTree获取选定的文件名和路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图从JTree-TreeSelectionListener中获取带有路径的选定文件名,我陷入了困境!请给我指导,以获取带有路径的文件名,到目前为止,我已经尝试了复制完整的代码.

Trying to get selected filename with path from the JTree - TreeSelectionListener, I got stuck on this! Please give me direction to get the filename with path, have copied the complete code so far I tried.

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

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

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

Trying to loop thro' to get value but wasn't successful! please give me directions, Thx

推荐答案

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

The first thing you need to do, is update FileTreeNode to provide a getter to return the File which this node represents...

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

    public File getFile() {
        return file;
    }

接下来,在您的TreeSelectionListener中,您需要获取selectionPath,获取lastPathComponent,测试以查看它是否为FileTreeNode并获取它代表的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...

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);
            }
        }
    }
});

这篇关于从JTree获取选定的文件名和路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆