简体   繁体   English

JTree如何显示文件名?

[英]How does JTree display file name?

In my project, I am trying to add a file explorer so the user can select files from a given directory. 在我的项目中,我正在尝试添加文件资源管理器,以便用户可以从给定目录中选择文件。 I want to limit this view to the project's root folder (which is determined by the user). 我想将此视图限制为项目的根文件夹(由用户确定)。 This is very much like Eclipses Package Explorer, as the "workspace" is determined by the user. 这与Eclipses Package Explorer非常相似,因为“工作区”由用户决定。

Currently files do not display the full path (from C:) which is what I want, but all of the folders display the full path (Which I do not want, i just want the folder name). 目前文件不显示完整路径(从C :)这是我想要的,但所有文件夹显示完整路径(我不想要,我只想要文件夹名称)。

So how does JTree display these names? 那么JTree如何显示这些名称?

I have seen around that JTree uses the File.tostring() method, but when I implemented my own file and overwrote the toString method, nothing changed. 我已经看到JTree使用File.tostring()方法,但是当我实现自己的文件并覆盖toString方法时,没有任何改变。

Here is my code: 这是我的代码:

import java.awt.BorderLayout;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.util.Collections;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

public class pnl_fileView extends JPanel {
    /**
     * Display a file system in a JTree view
     * 
     * @version $Id: FileTree.java,v 1.9 2004/02/23 03:39:22 ian Exp $
     * @author Ian Darwin
     */
    /** Construct a FileTree */

    //  public pnl_fileView(){
    private myFile projectFile;
    public pnl_fileView(myFile dir) {
        //Create file explorer
        //Need to add setup for root folder change.
        //Config.getProject(); //This gets the current file from the config file.
        //Begin choose File
        if(projectFile == null){
            JFileChooser chooser;
            String choosertitle = "Please Choose a Root Folder";
            chooser = new JFileChooser(); 
            chooser.setCurrentDirectory(new java.io.File("."));
            chooser.setDialogTitle(choosertitle);
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            //
            // disable the "All files" option.
            //
            chooser.setAcceptAllFileFilterUsed(false);
            //    
            if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
                System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
                System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
                projectFile = new myFile(chooser.getSelectedFile().getAbsolutePath());
                //projectFile = chooser.getSelectedFile();
            }
            else {
                System.out.println("No Selection ");
            }
        }
        else {
            // Figure out where in the filesystem to start displaying
        }

        //End choose file
        setLayout(new BorderLayout());

        // Make a tree list with all the nodes, and make it a JTree
        JTree tree = new JTree(addNodes(null, projectFile));

        // Add a listener
        tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) e
                        .getPath().getLastPathComponent();
                System.out.println("You selected " + node);
            }
        });

        // Lastly, put the JTree into a JScrollPane.
        JScrollPane scrollpane = new JScrollPane();
        scrollpane.getViewport().add(tree);
        add(BorderLayout.CENTER, scrollpane);
    }

    /** Add nodes from under "dir" into curTop. Highly recursive. */
    DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, myFile dir) {
        String curPath = dir.getPath();
        System.out.println(curPath);
        DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
        if (curTop != null) { // should only be null at root
            curTop.add(curDir);
        }
        Vector<String> ol = new Vector<String>();
        String[] tmp = dir.list();
        for (int i = 0; i < tmp.length; i++)
            ol.addElement(tmp[i]);
        Collections.sort(ol, String.CASE_INSENSITIVE_ORDER);
        myFile f;
        Vector<String> files = new Vector<String>();
        // Make two passes, one for Dirs and one for Files. This is #1.
        for (int i = 0; i < ol.size(); i++) {
            String thisObject = (String) ol.elementAt(i);
            String newPath;
            if (curPath.equals("."))
                newPath = thisObject;
            else
                newPath = curPath + myFile.separator + thisObject;
            System.out.println("this is the path: " + newPath);
            if ((f = new myFile(newPath)).isDirectory())
                addNodes(curDir, f);
            else
                files.addElement(thisObject);
        }
        // Pass two: for files.
        for (int fnum = 0; fnum < files.size(); fnum++)
            curDir.add(new DefaultMutableTreeNode(files.elementAt(fnum)));
        return curDir;
    }

    public Dimension getMinimumSize() {
        return new Dimension(200, 400);
    }

    public Dimension getPreferredSize() {
        return new Dimension(200, 400);
    }

    /** Main: make a Frame, add a FileTree */
    public static void main(String[] av) {

        JFrame frame = new JFrame("FileTree");
        frame.setForeground(Color.black);
        frame.setBackground(Color.lightGray);
        Container cp = frame.getContentPane();

        if (av.length == 0) {
            cp.add(new pnl_fileView(new myFile(".")));
        } else {
            cp.setLayout(new BoxLayout(cp, BoxLayout.X_AXIS));
            for (int i = 0; i < av.length; i++)
                cp.add(new pnl_fileView(new myFile(av[i])));
        }

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
class myFile extends File{
    public myFile(String pathname) {
        super(pathname);

    }
    public String toString() {
        return "Hello World!";
    }
    public String getAbsolutePath(){
        return "hi";
    }
}

In addition to JFileChooser , other examples of custom Java file explorers include these: 除了JFileChooser ,自定义Java文件浏览器的其他示例包括:

图片

图片

  • JTree with FileTreeModel , described here . JTreeFileTreeModel在这里描述。

图片

图片

图片

Personally, I wouldn't try and set the nodes display value by using some other object, I would leave that up to the TreeCellRenderer to decide. 就个人而言,我不会尝试通过使用其他对象来设置节点显示值,我会将其留给TreeCellRenderer来决定。 The main reason for this, is the data that is contained by the node might be need by some other part of the program. 其主要原因是程序的某些其他部分可能需要节点包含的数据。

在此输入图像描述

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
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;

public class TestFileTree extends JPanel {

    private File projectFile;

    public TestFileTree(File dir) {
        //Create file explorer
        //Need to add setup for root folder change.
        //Config.getProject(); //This gets the current file from the config file.
        //Begin choose File
        if (projectFile == null) {
            JFileChooser chooser;
            String choosertitle = "Please Choose a Root Folder";
            chooser = new JFileChooser();
            chooser.setCurrentDirectory(new java.io.File("."));
            chooser.setDialogTitle(choosertitle);
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            //
            // disable the "All files" option.
            //
            chooser.setAcceptAllFileFilterUsed(false);
            //    
            if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
                System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
                projectFile = new File(chooser.getSelectedFile().getAbsolutePath());
                //projectFile = chooser.getSelectedFile();
            } else {
                System.out.println("No Selection ");
            }
        } else {
            // Figure out where in the filesystem to start displaying
        }

        //End choose file
        setLayout(new BorderLayout());

        // Make a tree list with all the nodes, and make it a JTree
        JTree tree = new JTree(addNodes(null, projectFile));
        tree.setCellRenderer(new MyTreeCellRenderer());

        // Add a listener
        tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) e
                        .getPath().getLastPathComponent();
                System.out.println("You selected " + node);
            }
        });

        // Lastly, put the JTree into a JScrollPane.
        JScrollPane scrollpane = new JScrollPane();
        scrollpane.getViewport().add(tree);
        add(BorderLayout.CENTER, scrollpane);
    }

    /**
     * Add nodes from under "dir" into curTop. Highly recursive.
     */
    DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {
        DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(dir);
        if (curTop != null) { // should only be null at root
            curTop.add(curDir);
        }
        File[] tmp = dir.listFiles();
        Vector<File> ol = new Vector<File>();
        ol.addAll(Arrays.asList(tmp));
        Collections.sort(ol, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {

                int result = o1.getName().compareTo(o2.getName());

                if (o1.isDirectory() && o2.isFile()) {
                    result = -1;
                } else if (o2.isDirectory() && o1.isFile()) {
                    result = 1;
                }

                return result;
            }
        });
        // Pass two: for files.
        for (int fnum = 0; fnum < ol.size(); fnum++) {
            File file = ol.elementAt(fnum);
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);
            if (file.isDirectory()) {
                addNodes(node, file);
            }
            curDir.add(node);
        }
        return curDir;
    }

    public Dimension getMinimumSize() {
        return new Dimension(200, 400);
    }

    public Dimension getPreferredSize() {
        return new Dimension(200, 400);
    }

    public static void main(String[] av) {

        JFrame frame = new JFrame("FileTree");
        frame.setForeground(Color.black);
        frame.setBackground(Color.lightGray);
        Container cp = frame.getContentPane();

        if (av.length == 0) {
            cp.add(new TestFileTree(new File(".")));
        } else {
            cp.setLayout(new BoxLayout(cp, BoxLayout.X_AXIS));
            for (int i = 0; i < av.length; i++) {
                cp.add(new TestFileTree(new File(av[i])));
            }
        }

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {

        private FileSystemView fsv = FileSystemView.getFileSystemView();

        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            System.out.println(value);
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            if (value instanceof DefaultMutableTreeNode) {
                value = ((DefaultMutableTreeNode)value).getUserObject();
                if (value instanceof File) {
                    File file = (File) value;
                    if (file.isFile()) {
                        setIcon(fsv.getSystemIcon(file));
                        setText(file.getPath());
                    } else {
                        setIcon(fsv.getSystemIcon(file));
                        setText(file.getName());
                    }
                }
            }
            return this;
        }
    }
}

There are some "interesting" parts to your code. 您的代码中有一些“有趣”的部分。

While Vector isn't a bad choice, List (or in this case, specifically ArrayList ) is faster as it's not synchronized. 虽然Vector不是一个糟糕的选择,但List (或者在这种情况下,特别是ArrayList )更快,因为它没有同步。

Rather then using a loop to add elements to at list, use Arrays.asList(...) to convert the array to a list and use the List#addAll method (it's in Vector as well) 而不是使用循环将元素添加到列表中,使用Arrays.asList(...)将数组转换为列表并使用List#addAll方法(它也在Vector中)

I'm not sure what version of Java you're using, but you can now use for-each since Java 6 (I think), which would mean instead of for (int i = 0; i < ol.size(); i++) you could do for (String thisObject : ol) . 我不确定你正在使用什么版本的Java,但是你现在可以使用for-each Java 6(我认为),这意味着代替for (int i = 0; i < ol.size(); i++)你可以做for (String thisObject : ol)

Because you're using Generics in your lists, you don't need to cast the objects ;) 因为您在列表中使用泛型,所以不需要转换对象;)

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

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