How can I filter a JTable?

Posted by Jonas on Stack Overflow See other posts from Stack Overflow or by Jonas
Published on 2010-06-02T08:09:05Z Indexed on 2010/06/02 8:13 UTC
Read the original article Hit count: 426

Filed under:
|
|
|
|

I would like to filter a JTable, but I don't understand how I can do it. I have read How to Use Tables - Sorting and Filtering and I have tried with the code below, but with that filter, no rows at all is shown in my table. And I don't understand what column it is filtered on.

private void myFilter() {
    RowFilter<MyModel, Object> rf = null;
    try {
        rf = RowFilter.regexFilter(filterFld.getText(), 0);
    } catch (java.util.regex.PatternSyntaxException e) {
        return;
    }
    sorter.setRowFilter(rf);
}

MyModel has three columns, the first two are strings and the last column is of type Integer. How can I apply the filter above, consider the text in filterFld.getText() and only filter the rows where the text is matched on the second column?

I would like to show all rows that starts with the text specified by filterFld.getText(). I.e. if the text is APP then the JTable should contain the rows where the second column starts with APPLE, APPLICATION but not the rows where the second column is CAR, ORANGE.

I have also tried with this filter:

RowFilter<MyModel, Integer> itemFilter = new RowFilter<MyModel, Integer>(){
    public boolean include(Entry<? extends MyModel, ? extends Integer> entry){
        MyModel model = entry.getModel();
        MyItem item = model.getRecord(entry.getIdentifier());
        if (item.getSecondColumn().startsWith("APP")) {
            return true;
        } else {
            return false;
        }
    }
};

How can I write a filter that is filtering the JTable on the second column, specified by my textfield?

© Stack Overflow or respective owner

Related posts about java

Related posts about swing