有没有一种方法可以从没有getValueAt()复杂性的完整AbstractTableModel派生修剪的AbstractTableModel?

我的完整数据(包括userIds)已加载到JTable AbstractTableModel中。但是,出于显示目的,我希望派生与特定userId关联的数据的经过修剪的AbstractTableModel。

我开始认为这是不可能的,因为getValueAt会干预并引发IndexOutOfBounds异常?由于未填充已修剪的数据,因此似乎发生了这些异常。

public class PrunedUserIdTableModel extends AbstractTableModel {

    TableModel fullModel;
    List columnIdentifiers;
    List tempDatum;
    List tempData; // holds tempDatums
    int rowCount; // reports pruned rowCount through getRowCount() method
    List prunedData; // intended to hold data of matched userId rows

    public PrunedUserIdTableModel(JTable fullTable, String userId) {
        fullModel = fullTable.getModel();
        columnIdentifiers = new ArrayList();
        tempDatum = new ArrayList();
        tempData = new ArrayList();
        rowCount = 0;

        List<Integer> userCount = new ArrayList<>();

        // Load columnIdentifiers from fullModel; omitted here

        // Go through fullModel searching for rows with matching userIds

        for (int i = 0; i < fullModel.getRowCount(); i++) {
            for (int k = 0; k < fullModel.getColumnCount(); k++) {
                tempDatum.add(fullModel.getValueAt(i,k);
                if ((fullModel.getValueAt(i,k).equals(userId)) {
                    // Matching userId found; record relevant row
                    userCount.add(g);
                }
            }
            tempData.add(tempDatum);
            tempDatum.clear();
        }

        // Now populate prunedData
        for (int j = 0; j < userCount.size(); j++) {
            prunedData.add(tempData.get(userCount.get(j)));
            rowCount=rowCount+1;
        }

        fireTableChanged(null);
    }
    @Override
    public int getRowCount() {
        return rowCount;
    }
    @Override
    public int getColumnCount() {
        return fullModel.getColumnCount();
    }
    @Override
    public int getValueAt(int rowIndex, int columnIndex) {
        // THROWS INDEX OUT OF BOUNDS EXCEPTION: Index 0; size 0
        List rowList = (List)prunedData.get(rowIndex);
        return rowList.get(columnIndex);
    }
}

最佳答案

使用TableRowSorter过滤JTable行以仅显示所需的行。然后,当您通过索引引用某些内容时,请确保调用convertRowIndexToViewconvertRowIndexToModel

10-08 00:12