Get selected filename and path from JTree

2019-09-10 02:31发布

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.

EDIT: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

You selected viewgui.FileTreePanel$FileTreeNode@68556f62

Edit:2

Expected output -> G:\java_code\Temp\tempfile.txt

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

1条回答
一夜七次
2楼-- · 2019-09-10 03:12

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

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);
            }
        }
    }
});
查看更多
登录 后发表回答