How can I filter rows in a JTable?

somya agrawal picture somya agrawal · Jul 10, 2009 · Viewed 49.9k times · Source

i have a JTable having many strings in that.i have created a textbox for user entry, above the table. i want a row filter which can remove the rows having strings enterd by the user in the text box. please help me out for this.

Answer

Victor picture Victor · Jul 10, 2009

from here:
sorting and filtering

In the following example code, you explicitly create a sorter object so you can later use it to specify a filter:

MyTableModel model = new MyTableModel();
sorter = new TableRowSorter<MyTableModel>(model);
table = new JTable(model);
table.setRowSorter(sorter);

Then you filter based on the current value of a text field:

private void newFilter() {
    RowFilter<MyTableModel, Object> rf = null;
    //If current expression doesn't parse, don't update.
    try {
        rf = RowFilter.regexFilter(filterText.getText(),0);
    } catch (java.util.regex.PatternSyntaxException e) {
        return;
    }
    sorter.setRowFilter(rf);
}