java在对JTable进行排序后无法从中获取正确的行(Swing)
我得到了一个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);
}
}
下面的代码可以用数据填充my 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 楼答案
查看JTable中的方法
convertRowIndexToModel()
和convertRowIndexToView()
当对表进行排序时,视图中行的索引与模型中的索引不再匹配,您必须使用上述方法从索引转换到视图,反之亦然
例如,如果调用
JTable.getSelectedRow()
,将获得所选行的视图索引。必须将其转换为模型索引(使用convertRowIndexToModel()
),才能从模型中的列表中获取所选对象