Dynamic filter provides a search box above the tree and filters elements on the tree as user types it. In this article, I will talk about how to add dynamic filtering capabilities to your tree. I will also explain about how to customize the default filter.
Adding dynamic filter:
Adding dynamic filter to the tree is very easy. Instead of creating treeviewer directly, you need to create FilteredTree (org.
PatternFilter filter = new PatternFilter();
FilteredTree tree = new FilteredTree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, filter);
this.treeViewer = tree.getViewer();
and that's all you need to do to have dynamic filtering in your tree. Isn't that amazing! I know how hard it is to do in Swing.
When your view initially comes up, it would have a text box above your tree. By default it says "type filter text". But you can change that by calling setInitialText(String text) method on the FilteredTree.
If you see above, the constructor for FilteredTree takes PatternFilter. By default, it does word matching and it matches the beginning of every word in your text. In the previous article, we discussed about how to create filters. You would create a similar filter, but which extends PatternFilter (implement just the select method like in any filter) and pass it to FilteredTree.
To customize the pattern in PatternFilter, you could use the void setPattern(String pattern) in PatternFilter. You can set the pattern string using which this filter should select elements in the viewer. This is a public method.
You can also override methods like boolean isElementSelectable(Object element) (Answers whether the given element is a valid selection in the filtered tree), boolean isElementVisible(Viewer viewer, Object element) (Answers whether the given element in the given viewer matches the filter pattern), boolean isParentMatch(Viewer viewer, Object element), boolean isLeafMatch(Viewer viewer, Object element) and boolean wordMatches(String text) to customize the filter.
wordMatches tells if any of the words in the given text satisfy the filter criteria. You could override this method if you want your filter to behave differently. For example, instead of matching every word, you can override this method so that it matches the whole string or just the first word in your string etc.,
We saw how to create a dynamic filter and attach it to the tree. Also, we saw how to customize the pattern filter.