How can I filter rows in a JTable?
Asked Answered
G

4

7

I have a JTable with many strings in it. I have created a textbox for user entry, above the table. I want a row filter which can remove the rows having strings entered by the user in the text box. Please help me out for this.

Gelinas answered 10/7, 2009 at 5:51 Comment(2)
do you want to display only rows with the text or to not display rows with the text?Braden
If you are allowed, you could use GlazedLists. It has samples about auto-completion and table filtering.Mister
B
12

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);
}
Braden answered 10/7, 2009 at 6:5 Comment(0)
F
6

This few line solution seems to work:

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) 
{                                            
    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(((DefaultTableModel) jTable1.getModel())); 
    sorter.setRowFilter(RowFilter.regexFilter(jTextField1.getText()));

    jTable1.setRowSorter(sorter);
}  
Fewer answered 23/6, 2016 at 10:30 Comment(0)
B
2

You can use JTable.setAutoCreateRowSorter which will use the default row sorter/filter of the JTable

Barclay answered 10/7, 2009 at 6:25 Comment(0)
G
1

To pick up the comment from kd304, you could use GlazedLists. There you'll use a FilterList as the input for your JTable, and the FilterList will take care of the rest.

Ghana answered 10/7, 2009 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.