javaswingarraylistjlistdefaultlistmodel

Java Jframe issue updating Jlist replace entire list using arrayList of object


this is my first time asking for help here, sorry if I did something wrong, let me know please. I'm a native spanish speaker, sorry for some text being on spanish. I'm just starting on java so if you see issues on my code (apart of what I'm asking for) please let me know, thank you.

Explaning the code: I have a form that gets four Strings by "JtextFields" and place them on the attributes of my object "cliente1" from the class "Cliente" just after you press a button (by btAgregarRegistro listener). Then I add the object to an arrayList

//Arraylist declaration
private List<Cliente> arregloClientes = new ArrayList<>();

//Add the object to the ArrayList
                arregloClientes.add(cliente1);

and then I update the Jlist "listClientes" (on the function actualizarLista()) so you can see it on the form just after adding the record. That update calls a method of the class (Cliente) getDatosClientes that brings all the attributes to the DefaultListModel and then shows it on the Jlist My issue: When I add a new record, the last one I add, replace the entire list and so. So the first print of my method "getDatosClientes()" is good, but the second, replace the first one on the list. I would say the issue is on the update, but I've tried a lot of things and nothing seems to work. I hope I explained myself propertly. Thank you very much!

Here is all the code:

Main.java (main)

package nickoos;

public class Main
{
    public static void main(String[] args)
    {
        Formulario1();

    }

    public static void Formulario1()
    {
        Formulario frame1 = new Formulario(); //instanciar
        frame1.setContentPane(new Formulario().getPanel()); //mostrar el panel
        frame1.show();
        frame1.setSize(800,600);
        frame1.setLocation(600,230);
    }

}

Cliente.java (class)

package nickoos;

public class Cliente
{
    private String nombre;
    private String apellido;
    private String email;
    private String telefono;

    public Cliente(String nombre, String apellido, String email, String telefono)
    {
        this.nombre = nombre;
        this.apellido = apellido;
        this.email = email;
        this.telefono = telefono;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getApellido() {
        return apellido;
    }

    public void setApellido(String apellido) {
        this.apellido = apellido;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelefono() {
        return telefono;
    }

    public void setTelefono(String telefono) {
        this.telefono = telefono;
    }

    public String getDatosClientes()
    {
        return "Nombre: " + getNombre() + " Apellido: " + getApellido() + " Email: " + getEmail() + " Teléfono: " + getTelefono();
    }
}

Formulario.java (form)

package nickoos;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class Formulario extends JFrame {
    private JButton btAgregarRegistro;
    private JPanel panel;
    private JLabel lbTitulo;
    private JLabel lbNombre;
    private JTextField txNombre;
    private JLabel lbApellido;
    private JLabel lbInstrucciones;
    private JLabel lbSimetria;
    private JLabel lbEmail;
    private JLabel lbTelefono;
    private JTextField txApellido;
    private JTextField txEmail;
    private JTextField txTelefono;
    private JList listClientes;
    private JLabel lbSubtituloLista;
    private JButton btEliminarRegistro;
    private JButton btModificarRegistro;
    private List<Cliente> arregloClientes = new ArrayList<>();

    //Instance the class
    Cliente cliente1 = new Cliente("","","","");


    public JPanel getPanel() {
        return panel;
    }


    public Formulario()
    {
        //Listener to add a record
        btAgregarRegistro.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {

                //Set the attributes to the object 
                cliente1.setNombre(txNombre.getText());
                cliente1.setApellido(txApellido.getText());
                cliente1.setEmail(txEmail.getText());
                cliente1.setTelefono(txTelefono.getText());

                //Add the object to the ArrayList
                arregloClientes.add(cliente1);

                //Update the list
                actualizarLista();

                //Clear textFields after adding the record
                blanquearCampos();
            }
        });

        //Listener "delete"
        btEliminarRegistro.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                int indice = listClientes.getSelectedIndex();
                arregloClientes.remove(indice);
                actualizarLista();

            }
        });
    }

    //Clear textFields
    private void blanquearCampos()
    {
        txNombre.setText("");
        txApellido.setText("");
        txEmail.setText("");
        txTelefono.setText("");
    }

    //Update list
    private void actualizarLista()
    {
        DefaultListModel datos = new DefaultListModel();

        for (int i = 0; i < arregloClientes.size(); i++)
        {
            Cliente index = arregloClientes.get(i);
            datos.addElement(index.getDatosClientes());
        }
        listClientes.setModel(datos);
    }

}


Solution

  • Move this line

    //Instance the class
    Cliente cliente1 = new Cliente("","","","");
    

    Into this method

    btAgregarRegistro.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
    
                //move it HERE
    
                    //Set the attributes to the object 
                    cliente1.setNombre(txNombre.getText());
                    cliente1.setApellido(txApellido.getText());
                    cliente1.setEmail(txEmail.getText());
                    cliente1.setTelefono(txTelefono.getText());
    
                    //Add the object to the ArrayList
                    arregloClientes.add(cliente1);
    
                    //Update the list
                    actualizarLista();
    
                    //Clear textFields after adding the record
                    blanquearCampos();
                }
            });
    

    What is happening is you are referencing the same object in memory and just changing its values. What you want to do is to create a new object every time you want to add a Client.