Client Side Filtering

Once the data has been retrieved from the server, it can be filtered in the client without sending any requests to the server.

The first step is to attach an event listener to the Apply Filter button we added when building the app. In it we will call the applyFilterToTable method passing in the string from the textFieldFilter textfield.

btnApplyFilter.addActionListener(actionEvent -> {
    applyFilterToTable(this.textFieldFilter.getText());
});

In applyFilterToTable we harness the power of JTable and its underlying data model. We define a RowFilter object which will take a TableModel and an Object as arguments. Then we create a TableRowSorter which takes the table model of our Tasks table.

We then check to see if the text we want to filter has a length of 0 or not. If its zero, then we remove the TableRowSorter which clears the filter and displays all of our tasks again.

If the length of textToFilterBy is greater than 0 we add the TableRowSorter to the table, and then create a RowFilter object with the text from the textFieldFilter textfield as its regular expression. We then apply the filter to the TableRowSorter by calling setRowFilter.

Note: the user would be able to take advantage of the power of Java's pattern matching features.

If the length of the textToFilterBy is 0, then we remove the RowSorter by passing in null which will display all of the rows again.

private void applyFilterToTable(String textToFilterBy) {
    RowFilter<TableModel, Object> rf = null;
    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(this.table.getModel());
    
    if (textToFilterBy.length() != 0) {
        table.setRowSorter(sorter);

        try {
            rf = RowFilter.regexFilter(textToFilterBy);
        } catch (java.util.regex.PatternSyntaxException e) {
            System.out.printf("PatternSyntaxException: %s\n", e);
            return;
        }
        
        sorter.setRowFilter(rf);
    } else {
        table.setRowSorter(null);
    }
}

Run the app again

The app running with no filtering occuring

Enter some text in the filter text box, here we use "NoMatch" and the press the apply filter button. As you can see no match is found.

Filter finding no matches

Change the text in the filter text box to something we know is in a task, here the text filter

Filter finding a match

The only thing left to do is summarize what we've done.