8. Filter content
In addition to sort the table, the RowSorter class enable also to filter the content of the table. We can use for that the setRowFilter method who takes a RowFilter in parameter. RowFilter has several static methods to easily create filters. So we have methods to make “and” or “or” operations on filters. Moreover we’ve also a very useful method to create a regex filter for one or more columns.
We will add a button to filter on the “name” and “firstname” columns :
private class FilterAction extends AbstractAction {
private FilterAction() {
super("Filter");
}
public void actionPerformed(ActionEvent e) {
String regex = JOptionPane.showInputDialog("Filter regex : ");
sorter.setRowFilter(RowFilter.regexFilter(regex, 0, 1));
}
}
Like you can see, it’s very easy to filter the content of table on one or several columns. Here is the result with a filter “mp” :
For flexibility, you can also extends RowFilter who has only one methods include(Entry entry) who indicates if a line must be included in the table or not.
