JTree:如何检查当前节点是否是一个文件 [英] JTree: how to check if current node is a file

查看:187
本文介绍了JTree:如何检查当前节点是否是一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来填充正确工作的JTree

I am using the following code to populate a JTree which is working perfectly

File [] children = new File(directory).listFiles(); // list all the files in the directory
for (int i = 0; i < children.length; i++) { // loop through each
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());
    // only display the node if it isn't a folder, and if this is a recursive call
    if (children[i].isDirectory() && recursive) {
        parent.add(node); // add as a child node
        listAllFiles(children[i].getPath(), node, recursive); // call again for the subdirectory
    } else if (!children[i].isDirectory()){ // otherwise, if it isn't a directory
        parent.add(node); // add it as a node and do nothing else
    }
}

给出目录字符串,它将该目录中的所有文件添加到JTree,我的问题是我无法从每个节点获取文件...我知道您可以使用

Give a directory string, it adds all the files in that directory to the JTree, my problem is that i am unable to get the file from each of the nodes... i know you can use

jtree.getLastSelectedPathComponent()

获取最后一个选定的组件,但是我真的要检查所选组件是否类型为文件,如果是,则返回该文件的路径...有没有知道如何做到这一点?

to get the last selected component but what i really what is to check if the selected component is of type File and if it is, return the path of that file... does anyone know how to do this?

推荐答案

这是一个或多或少像你的小片段(如果你这样做会更容易可能提供了一个 SSCCE )。基本上,我将与 DefaultMutableTreeNode 相关联的用户对象从 String 更改为 / code>。我还添加了一个定制的 TreeCellRenderer 来仅显示文件的名称(而不是其绝对路径),而 TreeSelectionListener 向控制台输出当前选定的文件对象。

Here is a small snippet looking more or less like yours (it would have been easier if you could have provided an SSCCE). Basically, I changed the user object associated with the DefaultMutableTreeNode from a String to a File. I also added a customized TreeCellRenderer to only display the name of the File (and not its absolute path), and a TreeSelectionListener that outputs to the console the current selected File object.

import java.awt.Component;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;

public class TestTreeFile {

    protected void initUI() {
        JFrame frame = new JFrame(TestTreeFile.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTree tree = new JTree(createTreeModel(new File(System.getProperty("user.dir")), true));
        tree.setCellRenderer(new DefaultTreeCellRenderer() {
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row,
                    boolean hasFocus) {
                super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
                if (value instanceof DefaultMutableTreeNode) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                    if (node.getUserObject() instanceof File) {
                        setText(((File) node.getUserObject()).getName());
                    }
                }
                return this;
            }
        });
        tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {
                Object object = tree.getLastSelectedPathComponent();
                if (object instanceof DefaultMutableTreeNode) {
                    Object userObject = ((DefaultMutableTreeNode) object).getUserObject();
                    if (userObject instanceof File) {
                        File file = (File) userObject;
                        System.err.println("Selected file" + file.getAbsolutePath() + " Is directory? " + file.isDirectory());
                    }
                }
            }
        });
        JScrollPane pane = new JScrollPane(tree);
        frame.add(pane);
        frame.setSize(400, 600);
        frame.setVisible(true);
    }

    private DefaultMutableTreeNode createTreeModel(File file, boolean recursive) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);
        if (file.isDirectory() && recursive) {
            File[] children = file.listFiles(); // list all the files in the directory
            if (children != null) {
                for (File f : children) { // loop through each
                    node.add(createTreeModel(f, recursive));
                }
            }
        }
        return node;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestTreeFile().initUI();
            }
        });
    }
}

您可能还想看看这个< a href =https://codereview.stackexchange.com/questions/4446/file-browser-gui>文件浏览器GUI 。

这篇关于JTree:如何检查当前节点是否是一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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