简体   繁体   English

目录中的 Java JTree(显示完整路径而不仅仅是文件名)

[英]Java JTree from directory (shows full path instead of just the name of the file)

I wanted to make a tree from an existing directory, so that it shows all of the subfolders and files inside.我想从现有目录制作一棵树,以便显示其中的所有子文件夹和文件。 I did it with this code:我用这个代码做到了:

File file = new File(path); TreeModel model = new FileTreeModel(file); JTree tree = new JTree(model);

But now it shows the full path instead of just the folder/file name.但现在它显示完整路径,而不仅仅是文件夹/文件名。 If you don't know what I mean, this might help:如果你不明白我的意思,这可能会有所帮助: 爪哇树 Please help... I wanted to find the solution online but I didn't know how to describe the problem.请帮助... 我想在网上找到解决方案,但我不知道如何描述问题。 :/ :/

import java.io.File;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

class FileTreeModel implements TreeModel {
    private final ArrayList<TreeModelListener>  mListeners  = new ArrayList<>();
    private final MyFile                        mFile;

    public FileTreeModel(final MyFile pFile) {
        mFile = pFile;
    }
    @Override public Object getRoot() {
        return mFile;
    }
    @Override public Object getChild(final Object pParent, final int pIndex) {
        return ((MyFile) pParent).listFiles()[pIndex];
    }
    @Override public int getChildCount(final Object pParent) {
        return ((MyFile) pParent).listFiles().length;
    }
    @Override public boolean isLeaf(final Object pNode) {
        return !((MyFile) pNode).isDirectory();
    }
    @Override public void valueForPathChanged(final TreePath pPath, final Object pNewValue) {
        final MyFile oldTmp = (MyFile) pPath.getLastPathComponent();
        final File oldFile = oldTmp.getFile();
        final String newName = (String) pNewValue;
        final File newFile = new File(oldFile.getParentFile(), newName);
        oldFile.renameTo(newFile);
        System.out.println("Renamed '" + oldFile + "' to '" + newFile + "'.");
        reload();
    }
    @Override public int getIndexOfChild(final Object pParent, final Object pChild) {
        final MyFile[] files = ((MyFile) pParent).listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i] == pChild) return i;
        }
        return -1;
    }
    @Override public void addTreeModelListener(final TreeModelListener pL) {
        mListeners.add(pL);
    }
    @Override public void removeTreeModelListener(final TreeModelListener pL) {
        mListeners.remove(pL);
    }

    /**
     *  stolen from http://developer.classpath.org/doc/javax/swing/tree/DefaultTreeModel-source.html
     *
      * <p>
      * Invoke this method if you've modified the TreeNodes upon which this model
      * depends. The model will notify all of its listeners that the model has
      * changed. It will fire the events, necessary to update the layout caches and
      * repaint the tree. The tree will <i>not</i> be properly refreshed if you
      * call the JTree.repaint instead.
      * </p>
      * <p>
      * This method will refresh the information about whole tree from the root. If
      * only part of the tree should be refreshed, it is more effective to call
      * {@link #reload(TreeNode)}.
      * </p>
      */
    public void reload() {
        // Need to duplicate the code because the root can formally be
        // no an instance of the TreeNode.
        final int n = getChildCount(getRoot());
        final int[] childIdx = new int[n];
        final Object[] children = new Object[n];

        for (int i = 0; i < n; i++) {
            childIdx[i] = i;
            children[i] = getChild(getRoot(), i);
        }

        fireTreeStructureChanged(this, new Object[] { getRoot() }, childIdx, children);
    }

    /**
     * stolen from http://developer.classpath.org/doc/javax/swing/tree/DefaultTreeModel-source.html
     *
     * fireTreeStructureChanged
     *
     * @param source the node where the model has changed
     * @param path the path to the root node
     * @param childIndices the indices of the affected elements
     * @param children the affected elements
     */
    protected void fireTreeStructureChanged(final Object source, final Object[] path, final int[] childIndices, final Object[] children) {
        final TreeModelEvent event = new TreeModelEvent(source, path, childIndices, children);
        for (final TreeModelListener l : mListeners) {
            l.treeStructureChanged(event);
        }
    }
}

class MyFile {
    private final File mFile;

    public MyFile(final File pFile) {
        mFile = pFile;
    }

    public boolean isDirectory() {
        return mFile.isDirectory();
    }

    public MyFile[] listFiles() {
        final File[] files = mFile.listFiles();
        if (files == null) return null;
        if (files.length < 1) return new MyFile[0];

        final MyFile[] ret = new MyFile[files.length];
        for (int i = 0; i < ret.length; i++) {
            final File f = files[i];
            ret[i] = new MyFile(f);
        }
        return ret;
    }

    public File getFile() {
        return mFile;
    }

    @Override public String toString() {
        return mFile.getName();
    }
}

public class FileWrapperDeluxe {
    public static void main(final String[] args) {
        final JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        f.setBounds(100, 100, 400, 400);

        final File file = new File("E:\\");
        final MyFile mf = new MyFile(file);
        final TreeModel model = new FileTreeModel(mf);

        final JTree tree = new JTree(model);
        tree.setEditable(true);

        f.add(new JScrollPane(tree));
        f.setVisible(true);
    }
}

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

相关问题 来自文件路径的 Java JTree 目录结构 - Java JTree directory structure from file paths 如何在 JTree 中显示完整的文件路径? - How to display full file path in JTree? Java Servlet和JSP,如何从文件获取完整路径名? - Java Servlet and JSP, How to get full path name from a file? 从位于Java目录中的文件名获取文件路径 - Getting file path from file name located in a directory in java 如何在Java中使用文件名获取完整目录 - How to get the full directory in java with the file name 从绝对文件路径创建动态JTree - Creating dynamic JTree from absolute file path 如何从Java中的路径获取目录名? - How to get directory name from path in Java? 如何使用 Java 8 在 Spring Boot 中获取目录(不是文件)的完整系统路径 - How to get the full system path of a directory (not file) in Spring boot with Java 8 如何使用带有空格的文件夹名称的参数(即具有完整路径的文件名)从Java运行bat文件 - How to run bat file from java with arguments (i.e file name with full path) having folder name with space 使用大目录存储的嵌套目录将文件名转换为完整目录路径的优化方法 - Optimized way to Convert file name into full directory path using nested directory for large file storage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM