Problem when saving objects in an array?

0

I'm new here, and I'm into the world of java and in particular with an error, this is my Persona class, and this is my first question in this forum. I'm new to Java.

package persona;

public class Persona {

    private String nombre;
    private String apellidoPat;
    private int edad;

    public Persona(String nombre, String apellidoPat, int edad) {
        this.nombre = nombre;
        this.apellidoPat = apellidoPat;
        this.edad = edad;
    }

    public String getNombre() {
        return nombre;
    }

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

    public String getApellidoPat() {
        return apellidoPat;
    }

    public void setApellidoPat(String apellidoPat) {
        this.apellidoPat = apellidoPat;
    }

    public int getEdad() {
        return edad;
    }

    public void setEdad(int edad) {
        this.edad = edad;
    }
}

Y esta es mi clase principal

package persona;

import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;

public class Principal extends JFrame {

    Persona p[] = new Persona[2];

    public JPanel panel1;
    public JPanel panel2;
    public JPanel panel3;

    public JLabel label1;
    public JLabel label2;
    public JLabel label3;

    public JTextField txtNombre;
    public JTextField txtApellidoPat;
    public JTextField txtEdad;

    public JButton btnGuardar;
    public JButton btnRegistrados;
    public JButton btnLimpiar;
    public JButton btnSalir;

    //Aquí dentro del constructor, inicializo y creo las instancias 
     correspondientes de los objetos declarados
    public Principal() {
        super();
        this.setSize(550, 320);
        this.setTitle("Registro de usuarios");
        this.setResizable(false);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        panel1 = new JPanel(new GridLayout(2, 4));
        panel2 = new JPanel(new GridLayout(3, 2));
        panel3 = new JPanel(new GridLayout(1, 6));

        label1 = new JLabel("Nombre:");
        label1.setFont(new Font("arial", Font.BOLD, 25));
        label2 = new JLabel("Apellido Paterno:");
        label2.setFont(new Font("arial", Font.BOLD, 25));
        label3 = new JLabel("Edad:");
        label3.setFont(new Font("arial", Font.BOLD, 25));

        txtNombre = new JTextField("");
        txtNombre.setFont(new Font("arial", Font.PLAIN, 20));
        txtApellidoPat = new JTextField("");
        txtApellidoPat.setFont(new Font("arial", Font.PLAIN, 20));
        txtEdad = new JTextField("");
        txtEdad.setFont(new Font("arial", Font.PLAIN, 20));

        btnGuardar = new JButton("Guardar");
        btnGuardar.setFont(new Font("arial", Font.PLAIN, 20));
        btnRegistrados = new JButton("Ver registrados");
        btnRegistrados.setFont(new Font("arial", Font.PLAIN, 20));
        btnLimpiar = new JButton("Limpiar campos");
        btnLimpiar.setFont(new Font("arial", Font.PLAIN, 20));
        btnSalir = new JButton("Salir");
        btnSalir.setFont(new Font("arial", Font.PLAIN, 20));

        btnGuardar.setToolTipText("Guarda la información del usuario actual");
        btnRegistrados.setToolTipText("Ver usuarios registrados");
        btnLimpiar.setToolTipText("Limpia todos los campos");
        btnSalir.setToolTipText("Salir de la aplicación");

        Container contenedor = getContentPane();
        contenedor.add(panel1);
        panel1.add(panel2);
        panel1.add(panel3);

        panel2.add(label1);
        panel2.add(txtNombre);
        panel2.add(label2);
        panel2.add(txtApellidoPat);
        panel2.add(label3);
        panel2.add(txtEdad);

        panel3.add(btnGuardar);
        panel3.add(btnRegistrados);
        panel3.add(btnLimpiar);
        panel3.add(btnSalir);
        initComponents();
    }

    private void initComponents() {
        btnGuardar.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                    String nom, apep;
                    int edad;
                for (int i = 0; i < p.length; i++) {
                    nom = txtNombre.getText();
                    //p[i].setNombre(nom);
                    apep = txtApellidoPat.getText();
                    //p[i].setApellidoPat(apep);
                    edad = Integer.parseInt(txtEdad.getText());
                    //p[i].setEdad(edad);
                    p[i] = new Persona(nom,apep,edad);
                }
            }
        });

        btnRegistrados.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                String cad = "NOMBRE            APELLIDO PATERNO            EDAD            \n";
                for (int i = 0; i < p.length; i++) {
                    cad = cad + p[i].getNombre() + "                            "
                            + p[i].getApellidoPat() + "                             "
                            + p[i].getEdad() + "                "
                            + "\n";
                }
                JOptionPane.showMessageDialog(null, cad);
            }
        });
    }

    public static void main(String[] args) {
        Principal p1 = new Principal();
        p1.setVisible(true);
    }

}

At the time of executing and saving the first user that you add, it is saved, but when I add a second user, it replaces the first one that I added and when I want to see the users that I added, the last one appears twice (repeated ); What am I doing wrong? thanks

    
asked by Michael Ram 25.06.2018 в 17:15
source

1 answer

0

Good morning, I think the problem is when it comes to saving on a static vector. Let me explain a little, you have the following

public void actionPerformed(ActionEvent ae) {
                String nom, apep;
                int edad;
            for (int i = 0; i < p.length; i++) {
                nom = txtNombre.getText();
                //p[i].setNombre(nom);
                apep = txtApellidoPat.getText();
                //p[i].setApellidoPat(apep);
                edad = Integer.parseInt(txtEdad.getText());
                //p[i].setEdad(edad);
                p[i] = new Persona(nom,apep,edad);
            }
        }

What I can understand is that every time you save you enter the for cycle and the operator "i" returns to zero, for this reason it will always save you in the zero position of the vector.

Quick solution

Personally I use the ArrayList (they are vectors but simpler for the programmer). You could replace the next line - > Persona p[] = new Persona[2]; ... by List<Persona> p = new ArrayList(); and when you want to save forms the person object and add it to the array in the following way - >

p.add(new persona(nombre,apellido,edad));

This way you can create the people you want and they will be saved in a different position. When you want to go through the array you do it with a for

cycle
for(int i=0; i< p.size();i++)
{
  p.get(i).getNombre();
  p.get(i).getApellido();
  p.get(i).getEdad();
}

I hope I could help you.

    
answered by 26.06.2018 / 00:11
source