简体   繁体   English

JTree:如何检查当前节点是否是文件

[英]JTree: how to check if current node is a file

I am using the following code to populate a JTree which is working perfectly 我使用以下代码填充一个完美的JTree

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

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,我的问题是我无法从每个节点获取文件...我知道你可以使用

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? 获取最后选择的组件,但我真正要检查所选组件是否为File类型,如果是,返回该文件的路径...有谁知道如何做到这一点?

The DefaultMutableTreeNode you are using contains a 'userObject', which in your case is the String representing the name: 您正在使用的DefaultMutableTreeNode包含一个'userObject',在您的情况下是表示名称的String

DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());

If you would store the File in the node (or any unique identifier for a File ) you can retrieve it using the available getter . 如果你想存储File (一个或唯一标识符的节点File ),你可以使用检索它提供吸气

If you opt for this approach, you will probably have to change the renderer on the tree. 如果您选择此方法,则可能必须更改树上的渲染器。 A renderer with equivalent behavior can be implemented by extending the DefaultTreeCellRenderer and overriding the getTreeCellRendererComponent as follows 可以通过扩展DefaultTreeCellRenderer并覆盖getTreeCellRendererComponent来实现具有等效行为的渲染器,如下所示

@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus){
  Component result = super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasFocus );
  if ( value instanceof DefaultMutableTreeNode && ((DefaultMutableTreeNode)value).getUserObject() instanceof File ){
     ((JLabel)result).setText( (File)((DefaultMutableTreeNode)value).getUserObject()).getName() );
  }
}

Note: the code above is not tested. 注意:上面的代码未经过测试。 I hope I did not made any mistakes in my brackets, ... (too lazy to fire up my IDE) 我希望我的括号中没有出现任何错误,...(懒得启动我的IDE)

Here is a small snippet looking more or less like yours (it would have been easier if you could have provided an SSCCE ). 这是一个看起来或多或少与你相似的小片段(如果你能提供一个SSCCE会更容易)。 Basically, I changed the user object associated with the DefaultMutableTreeNode from a String to a File . 基本上,我将与DefaultMutableTreeNode关联的用户对象从String更改为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. 我还添加了一个自定义的TreeCellRenderer来显示File的名称(而不是它的绝对路径),以及一个TreeSelectionListener ,它向控制台输出当前选定的File对象。

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

You may also want to take a look at this File Browser GUI . 您可能还想查看此文件浏览器GUI

I'm using something like this: 我正在使用这样的东西:

private boolean isFileSelected()
{
    TreePath treePath = tree.getSelectionPath();
    Object lastPathComponent = treePath.getLastPathComponent();
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastPathComponent;

    return node.getUserObject() instanceof MyNodeObject;
}

MyNodeObject should be different from the folder data types so you can identify if the node is a file or not. MyNodeObject应该与文件夹数据类型不同,因此您可以识别节点是否是文件。

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

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