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

时间:2012-07-10 17:50:13

标签: java swing file directory jtree

我正在使用以下代码填充一个完美运行的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
    }
}

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

jtree.getLastSelectedPathComponent()

获取最后选择的组件,但我真正要检查所选组件是否为File类型,如果是,则返回该文件的路径...是否有人知道如何执行此操作?

3 个答案:

答案 0 :(得分:2)

您正在使用的DefaultMutableTreeNode包含'userObject',在您的情况下是代表名称的String

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

如果您要将File存储在节点中(或File的任何唯一标识符),您可以使用available getter检索它。

如果您选择此方法,则可能需要更改树上的渲染器。可以通过扩展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() );
  }
}

注意:上面的代码未经过测试。我希望我的括号中没有出现任何错误,......(懒得启动我的IDE)

答案 1 :(得分:2)

这是一个看起来或多或少与你相似的小片段(如果你能提供SSCCE会更容易)。基本上,我将与DefaultMutableTreeNode关联的用户对象从String更改为File。我还添加了一个自定义的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();
            }
        });
    }
}

您可能还想查看此File Browser GUI

答案 2 :(得分:0)

我正在使用这样的东西:

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

    return node.getUserObject() instanceof MyNodeObject;
}

MyNodeObject应与文件夹数据类型不同,以便您可以识别节点是否为文件。