Save to an ArrayList, the previous items are repeated

2

I have the following code to fill in a table, however when entering a second time information and save it, when the method updates the list, the data is duplicated, for example: If I enter Juan and save it shows Juan only, but at enter another name appears the name of the second object and Juan repeated twice

public void Listar_Contactos() {
    DefaultTableModel modelo = (DefaultTableModel) 
    Vista.VentanaAgenda.Tabla_contactos.getModel();
    Object datos[] = new Object[8];
    for (int i= 0; i< arreglo.size(); i++){
        datos[0]= arreglo.get(i).getFoto();
        datos[1]= arreglo.get(i).getNombre();
        datos[2]= arreglo.get(i).getApellido();
        datos[3]= Integer.toString(arreglo.get(i).getMovil());
        datos[4]= Integer.toString(arreglo.get(i).getCasa());
        datos[5]= arreglo.get(i).getPersonal();
        datos[6]= arreglo.get(i).getTrabajo();
        datos[7]= arreglo.get(i).getDireccion();
        modelo.addRow(datos);
    }

Array references an ArrayList created earlier and columns the tables are created with Netbeans.

I think it's because the method creates a second DefaultTableModel a apart from the one Netbeans creates for the table, but I do not know how to fix it

    
asked by David Calderon 11.06.2016 в 04:15
source

2 answers

1

The problem is that you only add information to the table, you never clean it. You should run this code first:

int filas = modelo.getRowCount();
for (int i = filas - 1; i >= 0; i--) {
    modelo.removeRow(i);
}

After that, execute the code to enter the values of your fix to the model.

    
answered by 11.06.2016 / 16:33
source
1

Friend is because the fix has to be instantiated within the for

for (int i= 0; i< arreglo.size(); i++){
    Object datos[] = new Object[8];
    datos[0]= arreglo.get(i).getFoto();
    datos[1]= arreglo.get(i).getNombre();
    datos[2]= arreglo.get(i).getApellido();
    datos[3]= Integer.toString(arreglo.get(i).getMovil());
    datos[4]= Integer.toString(arreglo.get(i).getCasa());
    datos[5]= arreglo.get(i).getPersonal();
    datos[6]= arreglo.get(i).getTrabajo();
    datos[7]= arreglo.get(i).getDireccion();
    modelo.addRow(datos);
}

that's the right way

    
answered by 11.06.2016 в 04:31