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

时间:2014-01-03 17:20:22

标签: 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);
    }
}

下面的代码可以用我的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();
}

一切对我来说都很好,当我对Jtable进行可见性调整时也没问题,问题是当我对Jtable中的特定行进行排序后,我对它进行了排序,该行没有更新。

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

1 个答案:

答案 0 :(得分:5)

查看JTable中的方法convertRowIndexToModel()convertRowIndexToView()

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

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