javajtableitextpdfptable

how to export the contents of a filtered jTable to a pdfpTable


I have a JTable and am using JFilter to filter its contents based on user input. Now i intend to export the contents of the JTable to a PdfPTable using iText library. The contents do not get copied correctly while using the filter.However the table is copied correctly if no filters are used,i.e. the user does not enter any text for filtering. I believe that its due to the contents not changing actually in the JTable as i am using a rowSorted as depicted here:

Filtering

TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(jTable.getModel());
jTable.setRowSorter(rowSorter);
jtfFilter.getDocument().addDocumentListener(new DocumentListener(){

    @Override
    public void insertUpdate(DocumentEvent e) {
        String text = jtfFilter.getText();

        if (text.trim().length() == 0) {
            rowSorter.setRowFilter(null);
        } else {
            rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
        }
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        String text = jtfFilter.getText();

        if (text.trim().length() == 0) {
            rowSorter.setRowFilter(null);
        } else {
            rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
        }
    }

Instantiating:

PdfPTable pdfTable = new PdfPTable(somejTable.getColumnCount());

Copying:

for(int i=0;i<rowCnt;i++)
    {
        for(int j=0;j<colCnt;j++)
        {
            Object val = table.getModel().getValueAt(i, j);
            if((val!=null))
                pdfTable.addCell(val.toString());
            else
                pdfTable.addCell("null");

        }
    }

So is there a way to get the exact filtered contents of the JTable? Do i need to use something like rowSorter on the PdfPTable as well ? Thanks.


Solution

  • You need to convert each table row index to the model row index by calling convertRowIndexToModel().

    See How can I get the filtered model