排序后无法从JTable获取正确的行(Swing)

Raf*_*Paz 0 java swing netbeans jtable abstracttablemodel

我有一个AbstractTableModel,像这样:

public class TableModelClienteFornecedor extends AbstractTableModel {

    private List<ClienteFornecedorDTO> linhas;
    private String[] colunas = new String[]{"Nome", "Conta"};

    public TableModelClienteFornecedor() {
        linhas = new ArrayList<>();
    }

    @Override
    public int getRowCount() {
        return linhas.size();
    }

    @Override
    public int getColumnCount() {
        return colunas.length;
    }

    @Override
    public String getColumnName(int column) {
        return colunas[column];
    }

     @Override
    public Class getColumnClass(int column) {
         return (getValueAt(0, column).getClass());        
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        ClienteFornecedorDTO cf = linhas.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return cf.getNome();

            case 1:
                return cf.getConta();

            default:
                throw new IndexOutOfBoundsException("Coluna incorreta");
        }
    }

    public void clear(JTable table) {
        table.setRowSorter(null);
        int indiceAntigo = this.getRowCount();
        linhas.clear();
        int indiceNovo = this.getRowCount();
        this.fireTableRowsDeleted(indiceAntigo, indiceNovo);
    }

    public boolean isEmpty() {
        return linhas.isEmpty();
    }

    public void add(ClienteFornecedorDTO cf) {
        linhas.add(cf);
        int index = this.getRowCount();
        fireTableRowsInserted(index, index);
    }

    public void addList(List<ClienteFornecedorDTO> list, JTable table) {
        int tamanhoAntigo = this.getRowCount();
        linhas.addAll(list);
        int tamanhoNovo = this.getRowCount() - 1;
        this.fireTableRowsInserted(tamanhoAntigo, tamanhoNovo);      
        table.setAutoCreateRowSorter(true);        
    }

    public ClienteFornecedorDTO get(int i) {
        return linhas.get(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

并且下面的代码可以用我的Jtable填充数据:

private void realizarBusca(String nome) {

    IContaDAO dao = new ContaDAO();
    boolean isFornecedor = radioFornecedor.isSelected();
    List<ClienteFornecedorDTO> retorno =
         dao.retornaContaClienteFornecedor(isFornecedor, nome);
    tableModelClienteFornecedor.clear();
    tableModelClienteFornecedor.addList(retorno, tableClienteFornecedor);
    tableClienteFornecedor.updateUI();
}
Run Code Online (Sandbox Code Playgroud)

一切都对我很好,当我对Jtable进行可视化处理时也没关系,问题是当我对我的Jtable中的特定行进行排序后,排序它没有更新.

任何人都可以帮助我吗?我很感激,因为我从昨天起就开始使用它,但仍无法找到解决问题的方法.

JB *_*zet 5

看看方法convertRowIndexToModel()convertRowIndexToView()JTable.

对表进行排序时,视图中行的索引不再与模型中的索引匹配,您必须使用上述方法从索引转换为视图,反之亦然.

例如,如果您调用JTable.getSelectedRow(),您将获得所选行的视图索引.您必须将其转换为模型索引(使用convertRowIndexToModel())才能从模型中的列表中获取所选对象.