Saturday, June 12, 2010

Multiple Row Filters for JTable

When using the JTable from Java's swing UI, one might often come across a requirement when data filters need to be combined to offer results from searching multiple columns ... the Java Tutorials cover the simple stuff but they don't talk about combining filters! What to do? You can just hit the javadocs and put the pieces together OR after you've read the simple stuff, just try this and it should work like magic:

RowFilter<TableModel, Object> firstFiler = null;
RowFilter<TableModel, Object> secondFilter = null;
List<RowFilter<TableModel,Object>> filters = new ArrayList<RowFilter<TableModel,Object>>();
RowFilter<TableModel, Object> compoundRowFilter = null;
try {
    firstFiler = RowFilter.regexFilter(yourRegexString, columnIndex);
    secondFilter = RowFilter.regexFilter(yourRegexString, columnIndex);
    filters.add(firstFiler);
    filters.add(secondFilter);
    compoundRowFilter = RowFilter.andFilter(filters); // you may also choose the OR filter
} catch (java.util.regex.PatternSyntaxException e) {
    return;
}
sorter.setRowFilter(compoundRowFilter);
Easy Huh?

4 comments:

  1. What if I need to set like 3 or four filters? and if he can choose to use all the filters or just one of them?

    ReplyDelete
  2. I broke my head, trying to achieve this filtering secuense, it was easy, damn

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete