Filtered JTree

C

ced

Hi,
I want to filter a JTree using the following model FilteredTreeModel.

In my case, my tree contains files & folders and I want to display
files that have a specific extension (my filter accepts folder and
files with this extension).
The model works fine except that it will display empty folders...
I can't find an easy way to avoid these empty folders :-(

Can someone help me please ?


public class FilteredTreeModel extends DefaultTreeModel {

public Filter filter;

public FilteredTreeModel(DefaultMutableTreeNode root, Filter filter)
{
super(root);
this.filter = filter;
}

public Object getChild(Object parent, int index) {

DefaultMutableTreeNode node = (DefaultMutableTreeNode) parent;
if(filter == null) {
return node.getChildAt(index);
}
else {

int pos = 0;
for(int i = 0, cnt = 0; i < node.getChildCount(); i++) {
if(filter.accepts(((DefaultMutableTreeNode)
node.getChildAt(i)).getUserObject())) {
if (cnt++ == index) {
pos = i;
break;
}
}
}
return node.getChildAt(pos);

}

}

public int getChildCount(Object parent) {

DefaultMutableTreeNode node = (DefaultMutableTreeNode) parent;
if (filter == null) {
return node.getChildCount();
}
else {

int childCount = 0;
Enumeration children = node.children();
while (children.hasMoreElements()) {

if (filter.accepts(((DefaultMutableTreeNode)
children.nextElement()).getUserObject())) {
childCount++;
}

}
return childCount;

}

}

public void setFilter(Filter filter) {

if (!this.filter.equals(filter)) {

this.filter = filter;
Object[] path = {root};
int[] childIndices = new int[root.getChildCount()];
Object[] children = new Object[root.getChildCount()];

for (int i = 0; i < root.getChildCount(); i++) {
childIndices = i;
children = root.getChildAt(i);
}

fireTreeStructureChanged(this, path, childIndices, children);

}

}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top