I'm in the process of writing a school project and I have one problem i can't solve. I have a tree that shows directories and file paths but I need to display only .mp3 and .wav files. Can someone give me some advice how to do that? I have a class with a tree model:
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();
}
String[] children = directory.list();
Wherever you are listing the children, like in the above, know that File.list()
can also take a FilenameFilter
. There is also a similar method called File.listFiles()
which can take a FileFilter
(very similar). Using one of these, you can filter your files by filename (which includes the extension).