Agregar varios objetos en un arraylist
Saludos, tengo un problema, estoy probando el funcionamiento del arraylist y quiero agregar varios objetos en dicho arraylist desde una ventana pero el programa sólo me agrega un único objeto y no se qué estoy haciendo mal. Anexo les envío los fuentes. Esto es sólo para agregar, aún no se como buscar, modificar y eliminar estoy empezando en esto de las colecciones. Tengo dos packages: Dominio e interfaz
Gracias de antemano por cualquier ayuda que puedan prestarme.
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Dominio;
/**
*
* @author Dayana
*/
public class Estudiante {
private long cedula;
private String nombres;
private String email;
public Estudiante()
{
this.cedula = 0;
this.nombres="";
this.email="";
}
public Estudiante(long cedula, String nombres, String email)
{ this.cedula = cedula;
this.nombres = nombres;
this.email = email;
}
public long getCedula() {
return cedula;
}
public void setCedula(long cedula){
this.cedula= cedula;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres){
this.nombres= nombres;
}
public String getEmail() {
return email;
}
public void setEmail(String email){
this.email= email;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Dominio;
import java.util.ArrayList;
/**
*
* @author Dayana
*/
public class ListaRegistroEstudiante {
private ArrayList<Estudiante> ListadoEstudiantes = new ArrayList<Estudiante>();
public ListaRegistroEstudiante(ArrayList<Estudiante> ListadoEstudiantes) {
this.ListadoEstudiantes = ListadoEstudiantes;
}
public ListaRegistroEstudiante() {
}
public ArrayList<Estudiante> getListadoEstudiantes() {
return ListadoEstudiantes;
}
public void setListadoEstudiantes(ArrayList<Estudiante> ListadoEstudiantes) {
this.ListadoEstudiantes = ListadoEstudiantes;
}
public void IncluirEstudiante(Estudiante E) {
this.ListadoEstudiantes.add(E);
}
public void imprimir (){
if (ListadoEstudiantes != null) {
for (Estudiante opc : ListadoEstudiantes) {
System.out.println("---------------");
System.out.println(opc.getCedula());
System.out.println(opc.getNombres());
System.out.println(opc.getEmail());
}
}
else {
System.out.println("No hay Estudiantes para mostrar");
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* AgregarEstudiante.java
*
* Created on 07/05/2010, 05:11:04 PM
*/
package Interfaz;
import Dominio.Estudiante;
import Dominio.ListaRegistroEstudiante;
/**
*
* @author Dayana
*/
public class AgregarEstudiante extends javax.swing.JFrame {
ListaRegistroEstudiante RegEst = new ListaRegistroEstudiante() ;
Estudiante EstudianteActual = new Estudiante();
/** Creates new form AgregarEstudiante */
public AgregarEstudiante() {
initComponents();
}
public AgregarEstudiante( ListaRegistroEstudiante E) {
initComponents();
this.RegEst = E;}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
BotonOK = new javax.swing.JButton();
CedulaTxt = new javax.swing.JTextField();
NombresTxt = new javax.swing.JTextField();
EmailTxt = new javax.swing.JTextField();
BotonImprimir = new javax.swing.JButton();
jButton1.setText("jButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Cédula");
jLabel2.setText("Nombre y Apellido");
jLabel3.setText("Correo Electrónico");
BotonOK.setText("OK");
BotonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BotonOKActionPerformed(evt);
}
});
NombresTxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NombresTxtActionPerformed(evt);
}
});
BotonImprimir.setText("Imprimir");
BotonImprimir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BotonImprimirActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(85, 85, 85)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(NombresTxt)
.addComponent(EmailTxt)
.addComponent(CedulaTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(105, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(BotonOK)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 147, Short.MAX_VALUE)
.addComponent(BotonImprimir)
.addGap(58, 58, 58))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(CedulaTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(NombresTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(61, 61, 61)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(EmailTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)))
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BotonOK)
.addComponent(BotonImprimir))
.addGap(25, 25, 25))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void NombresTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NombresTxtActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_NombresTxtActionPerformed
private void BotonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonOKActionPerformed
EstudianteActual.setNombres(NombresTxt.getText());
EstudianteActual.setCedula(Long.parseLong(CedulaTxt.getText()));
EstudianteActual.setEmail(EmailTxt.getText());
//RegEst.getListadoEstudiantes().IncluirEstudiante(EstudianteActual);
RegEst.IncluirEstudiante(EstudianteActual);
}//GEN-LAST:event_BotonOKActionPerformed
private void BotonImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonImprimirActionPerformed
RegEst.imprimir();
}//GEN-LAST:event_BotonImprimirActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AgregarEstudiante().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BotonImprimir;
private javax.swing.JButton BotonOK;
private javax.swing.JTextField CedulaTxt;
private javax.swing.JTextField EmailTxt;
private javax.swing.JTextField NombresTxt;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// End of variables declaration//GEN-END:variables
}
- Inicie sesión o regístrese para enviar comentarios
Lo sospeché desde un
Lo sospeché desde un principio:::
En la linea:::
EstudianteActual.setNombres(NombresTxt.getText());
en ese método siempre inicializa EstudianteActual con un nuevo objeto
EstudianteActual = new Estudiante();
y luego si asignale el resto:::
EstudianteActual.setNombres(NombresTxt.getText());
EstudianteActual.setCedula(Long.parseLong(CedulaTxt.getText()));
EstudianteActual.setEmail(EmailTxt.getText());
....
Lo probé y me funcionó bien.
----------------
Dejame darte unas recomendaciones ya que tienes la suerte que te esté escribiendo (soy de esos que solo preguntan en los fotos y poco ayudan... veamos si empiezo a mejorar)::::::::
Los objetos que crees, por ejemplo de la clase Estudiante... declararos empezando con minúsculas...........seria "estudianteActual"......... esto es una convención en la Prog orientada a objetos... permite identificar facilmente que es una clase y que es un objeto.
Las clases esas si deben empezar Siempre con Mayuscula inicial, por ejemplo::: ListaRegistroEstudiante ........... pero como ya te comento, su objeto debe empezar por minuscula inicial, seria bueno el mismo nombre de la clase "listaRegistroEstudiante."
Otro ejemplo seria::: ArrayList arrayListDeEstudiantes = new ArrayList();
---------------
Y otra recomendación es que los nombres de objetos y variables (que deben empezar con letra minuscula) sean lo mas descriptivos y claros posibles para que al leer por encima sus nombres se comprenda facilmente (sin enredarse) que son y que objetivo cumplen.
----
Bueno, te dejo un saludo.
Resuelto
Efectivamente, ya resolví el problema y muchas gracias por las recomendaciones, bienvenidas sean