How to filter strings in JTable?

I have a JTable that has a lot of lines in this. I created a text box for user input above the table. I want a line filter that can remove lines containing lines entered by the user in a text box. please help me for this.

+3
source share
4 answers

from here:
sorting and filtering

In the following code example, you explicitly create a sorter object so that you can use it later 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 the 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);
}
+8
source

This small linear solution works:

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);
}  
+5
source

You can use JTable.setAutoCreateRowSorterwhich will use the default string sorter / filterJTable

+2
source

To get a comment from kd304, you can use GlazedLists . There you will use the FilterList as an input for the JTable, and the FilterList will take care of the rest.

+1
source

Source: https://habr.com/ru/post/1712267/


All Articles