JTree - 仅具有固定文件扩展名的文件系统查看器树

时间:2014-06-20 19:13:23

标签: java file system jtree

我正在写一个学校项目,我有一个问题我无法解决。 我有一个显示目录和文件路径的树,但我只需要显示.mp3和.wav文件。有人可以给我一些建议怎么做吗? 我有一个树模型的课程:

public boolean isLeaf(Object node) {
    File file = (File) node;
    return file.isFile();
}

public int getIndexOfChild(Object parent, Object child) {
    File directory = (File) parent;
    File file = (File) child;
    String[] children = directory.list();
    for (int i = 0; i < children.length; i++) {
        if (file.getName().equals(children[i])) {
            return i;
        }
    }
    return -1;

}

public void valueForPathChanged(TreePath path, Object value) {
    File oldFile = (File) path.getLastPathComponent();
    String fileParentPath = oldFile.getParent();
    String newFileName = (String) value;
    File targetFile = new File(fileParentPath, newFileName);
    oldFile.renameTo(targetFile);
    File parent = new File(fileParentPath);
    int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) };
    Object[] changedChildren = { targetFile };
    fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);

}

private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
    TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    while (iterator.hasNext()) {
        listener = (TreeModelListener) iterator.next();
        listener.treeNodesChanged(event);
    }
}

public void addTreeModelListener(TreeModelListener listener) {
    listeners.add(listener);
}

public void removeTreeModelListener(TreeModelListener listener) {
    listeners.remove(listener);
}

private class TreeFile extends File {
    public TreeFile(File parent, String child) {
        super(parent, child);
    }

    public String toString() {
        return getName();
    }
}

String getFileDetails(File file) {
    if (file == null)
        return "";
    StringBuffer buffer = new StringBuffer();
    buffer.append("Name: " + file.getName() + "\n");
    buffer.append("Path: " + file.getPath() + "\n");
    buffer.append("Size: " + (double) (file.length() / 1024) / 1024 + " MB" + "\n");
    return buffer.toString();
}

1 个答案:

答案 0 :(得分:1)

String[] children = directory.list();

无论您在哪里列出孩子,如上所述,都知道File.list()也可以FilenameFilter。还有一种名为File.listFiles()的类似方法可以采用FileFilter(非常相似)。使用其中一个,您可以按文件名(包括扩展名)过滤文件。