javaswingjtablerowfilter

JTable Row Filter based on list of table model row integers


I'm building a query screen for my data table. I've done the work and consolidated the rows I want to show on the table based on user criteria.

How can I apply a row filter to a table based on the rows of the model? For instance: I want to show rows 3,6,7,8,9 which are stored in an ArrayList<Integer> list.

I am currently not grasping the RowFilter class. I'm not sure what to do or how to use it here:

RowFilter<DefaultTableModel,Integer> rf = new RowFilter<>() {
    @Override
    public boolean include(Entry entry) {
        // TODO Auto-generated method stub
        return false;
    }
};

Solution

  • After studying and trying to grasp how the RowFilter Class works, i got my table to sort the way i want it to, it seems. I still need to do more testing but it looks like it is working. I still do not fully grasp the RowFilter Class so i would love some feedback.

    Here is my code: where ArrayList<Integer> filteredRows = new ArrayList<>(); contains the row numbers i want to show. To my understanding, the filter automatically iterates over my table model and the identifier is the row number the filter is currently processing. So at first glance if the identifier equals any of the row numbers i have stored, then show it.

    RowFilter<DefaultTableModel,Integer> rf = new RowFilter<>() {
    
        @Override
        public boolean include(Entry<? extends DefaultTableModel, ? extends Integer> entry) {
            int entryRow = entry.getIdentifier();
            for (Integer i : filteredRows) {
                if (entryRow == i) return true;
            }
            return false;
        }
    
    };
    TableRowSorter<DefaultTableModel> sorter =  new TableRowSorter<DefaultTableModel>(myTableModel);
    sorter.setRowFilter(null);
    sorter.setRowFilter(rf);
    table.setRowSorter(sorter);