| Free tutorials for Java, Eclipse and Web programming |
Now we would like to add a filter to the table. The user should have a text field in which we can enter a first- or lastname. Only the names which applies to this filter should get displayed.
Adding a filter to a view is simple, you use method addFilter() on the viewer, which expects a ViewFilter as argument. Each ViewFilter is checked the input on the viewer is changed of whenever the viewer.refresh();
Create a new Class "de.vogella.jface.tableviewer.filter.PersonFilter.java"
package de.vogella.jface.tableviewer.filter;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import de.vogella.jface.tableviewer.model.Person;
public class PersonFilter extends ViewerFilter {
private String searchString;
public void setSearchText(String s) {
// Search must be a substring of the existing value
this.searchString = ".*" + s + ".*";
}
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (searchString == null || searchString.length() == 0) {
return true;
}
Person p = (Person) element;
if (p.getFirstName().matches(searchString)) {
return true;
}
if (p.getLastName().matches(searchString)) {
return true;
}
return false;
}
}
We will finally implement your search field functionality. Via the setFilter() and addFilter() methods such a filter can be added to a viewer. If more then one filter is defined all filters must be true for the table to display the data. Add to your text field a keyListener which updates the filter and the viewer. You need also to define a new field "private PersonFilter filter;" and change the method createPartControl().
private PersonFilter filter;
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(2, false);
parent.setLayout(layout);
Label searchLabel = new Label(parent, SWT.NONE);
searchLabel.setText("Search: ");
searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
| GridData.HORIZONTAL_ALIGN_FILL));
searchText.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
filter.setSearchText(searchText.getText());
viewer.refresh();
}
});
createViewer(parent);
comparator = new MyViewerComparator();
viewer.setComparator(comparator);
filter = new PersonFilter();
viewer.addFilter(filter);
}
}
Run the example, filtering should work.