1
I’m trying to fill a jtable with elements that are inside an arraylist, which is inside another object:
private void jButtonConfirmarProdutoActionPerformed(java.awt.event.ActionEvent evt) {
modProduto.setQuantidade(Integer.parseInt(jTextFieldQnt.getText()));
modVenda.itens.add(modProduto);
jTable1 = ctrl.fillTable(jTable1, modVenda);
}
These are the classes:
public class ModeloVenda {
private int idVenda;
private String data;
private float valorVenda;
private int idCliente;
public final ArrayList<ModeloProduto> itens;
}
public class ModeloProduto {
private int id_produto;
private String nome;
private float preco_compra;
private float preco_venda;
private int quantidade;
private int fornecedor;
public float calculaTotal(int quantidade){
return preco_venda*quantidade;
}}
This is the function that fills the table:
public JTable fillTable(JTable tabela, ModeloVenda mod){
ArrayList data = new ArrayList();
String[] Collums= new String[]{"Nome", "Valor Unitário", "Quantidade", "Valor Total"};
for(int i = 0; i < mod.itens.size(); i++){
dados.add(new Object[]{mod.itens.get(i).getNome(),
mod.itens.get(i).getPreco_venda(), mod.itens.get(i).getQuantidade(),
mod.itens.get(i).calculaTotal(mod.itens.get(i).getQuantidade())});
}
ModeloTabela modelo = new ModeloTabela(dados, Colunas);
tabela.setModel(modelo);
for(int i = 0; i<Colunas.length; i++){
tabela.getColumnModel().getColumn(i).setPreferredWidth(150);
tabela.getColumnModel().getColumn(i).setResizable(false);
}
tabela.getTableHeader().setReorderingAllowed(false);
tabela.setAutoResizeMode(tabela.AUTO_RESIZE_OFF);
tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
return tabela;
}
But when I add another element in the array and update the table all elements are replaced by the new:
your problem is in the
jButtonConfirmarProdutoActionPerformed
, you have to create a newmodProduto
for every time you add it to the list. You’re adding the same item over and over again without ever creating the new one, and even worse, you’re changing it over the course of the code– Sorack
@Sorack, thank you, that solved the problem, I thought the function arraylist.add created a new object and passed the parameters, not that it used the same object. Thank you
– Vitor Gabriel Andrade
@Sorack now that the question has reopened, it would be interesting to post your comment as an answer, to "close" the question as solved.
– user28595
@diegofm posted the reply, thank you!
– Sorack