| 
	
		|  Autor | Tema: Ayuda, obtener datos de Objetos en ArrayList  (Leído 8,990 veces) |  
	| 
			| 
					
						| touchi 
								
								 Desconectado 
								Mensajes: 8
								
								
								
								
								
								   | 
 
Tengo que realizar un programa el cual Cargue artículos, muestre todos los artículos cargado y luego en otra ventana de consulta muestre: cantidad de productos de cada tipo. total de dinero en artículos.  porcentaje de artículos de tipo 2.  Y articulo con el precio mas elevado. Ya realice la carga de artículos y la otra pantalla que muestra todos los artículos cargados. Mi problema es la ventana de consulta que muestra específicamente ciertos datos. Este es mi código, si alguien me puede dar una mano por favor. Tengo un examen pronto y la verdad que eso me esta complicando la vida. https://www.mediafire.com/?6tzn3g25uhv07fuMain Class
 MenuPrincipal class]public class Clase14Quiosco {      public static void main(String[]  args) {        MenuPrincipal v = new MenuPrincipal();        v.setVisible(true);    } }  
 AltaArticulo classimport java.util.ArrayList;import javax.swing.JOptionPane;  public class MenuPrincipal extends  javax.swing .JFrame {     private ArrayList<Articulo> listaArticulos;      public MenuPrincipal() {        initComponents();        listaArticulos = new ArrayList<>();    }      private void initComponents() {         jMenu1 = new  javax.swing .JMenu();        jMenu2 = new  javax.swing .JMenu();          jMenu1.setText("Articulos");            public void actionPerformed( java.awt .event .ActionEvent  evt) {                jMenu1ActionPerformed(evt);            }        });         jMenuItem1.setText("Alta");            public void actionPerformed( java.awt .event .ActionEvent  evt) {                jMenuItem1ActionPerformed(evt);            }        });        jMenu1.add(jMenuItem1);         jMenuBar1.add(jMenu1);         jMenu2.setText("Reportes");         jMenuItem2.setText("Listado");            public void actionPerformed( java.awt .event .ActionEvent  evt) {                jMenuItem2ActionPerformed(evt);            }        });        jMenu2.add(jMenuItem2);         jMenuBar1.add(jMenu2);         setJMenuBar(jMenuBar1);         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());        getContentPane().setLayout(layout);        layout.setHorizontalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGap(0 , 400 , Short .MAX_VALUE)        );        layout.setVerticalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGap(0 , 279 , Short .MAX_VALUE)        );         pack();    }// </editor-fold>                             private void jMenu1ActionPerformed( java.awt .event .ActionEvent  evt) {     }                                           private void jMenuItem1ActionPerformed( java.awt .event .ActionEvent  evt) {        AltaArticulo v = new AltaArticulo(listaArticulos);        v.setVisible(true);    }                                               private void jMenuItem2ActionPerformed( java.awt .event .ActionEvent  evt) {        ConsultaArticulos v = new ConsultaArticulos(listaArticulos);        v.setVisible(true);    }                                                // Variables declaration - do not modify                         private javax.swing .JMenu  jMenu1;    private javax.swing .JMenu  jMenu2;    // End of variables declaration                   }  
 ConsultaArticulos classimport java.util.ArrayList;import javax.swing.JOptionPane;  public class AltaArticulo extends  javax.swing .JFrame {     private ArrayList<Articulo> listaArticulos;     public AltaArticulo() {        initComponents();    }     public AltaArticulo(ArrayList<Articulo> listaArticulos) {        initComponents();        this.listaArticulos = listaArticulos;    }      private void initComponents() {         jLabel1 = new  javax.swing .JLabel();        jLabel2 = new  javax.swing .JLabel();        jLabel3 = new  javax.swing .JLabel();        jLabel4 = new  javax.swing .JLabel();        jLabel5 = new  javax.swing .JLabel();        jLabel6 = new  javax.swing .JLabel();        btnAgregar = new  javax.swing .JButton();          jLabel1.setText("Codigo");         jLabel2.setText("Nombre");         jLabel3.setText("Precio");         jLabel4.setText("Stock actual");         jLabel5.setText("Stock mínimo");         jLabel6.setText("Categoria");             public void actionPerformed( java.awt .event .ActionEvent  evt) {                txtCodigoActionPerformed(evt);            }        });          btnAgregar.setText("Agregar");            public void actionPerformed( java.awt .event .ActionEvent  evt) {                btnAgregarActionPerformed(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(46, 46, 46)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)                    .addComponent(jLabel2)                    .addComponent(jLabel1)                    .addComponent(jLabel6)                    .addComponent(jLabel5)                    .addComponent(jLabel3)                    .addComponent(jLabel4))                .addGap(18, 18, 18)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)                    .addComponent(btnAgregar)                    .addComponent( cboCategoria, 0 , javax.swing .GroupLayout .DEFAULT_SIZE , Short .MAX_VALUE)                    .addComponent(txtCodigo)                    .addComponent(txtNombre)                    .addComponent(txtPrecio)                    .addComponent(txtStockActual)                    .addComponent(txtStockMinimo))                .addContainerGap(41 , Short .MAX_VALUE))        );        layout.setVerticalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addGap(26, 26, 26)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(jLabel2))                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(txtStockActual, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(txtStockMinimo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                    .addComponent(cboCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))                .addGap(18, 18, 18)                .addComponent(btnAgregar)                .addContainerGap(24 , Short .MAX_VALUE))        );         pack();    }// </editor-fold>                             private void btnAgregarActionPerformed( java.awt .event .ActionEvent  evt) {        int codigo = Integer .parseInt( txtCodigo.getText());        String nombre =  txtNombre.getText();        float precio = Float .parseFloat( txtPrecio.getText());        int stockActual = Integer .parseInt( txtStockActual.getText());        int stockMinimo = Integer .parseInt( txtStockMinimo.getText());        int categoria = cboCategoria.getSelectedIndex()+1;         Articulo nuevo = new Articulo();         nuevo.setCodigo(codigo);        nuevo.setNombre(nombre);        nuevo.setPrecio(precio);        nuevo.setStockActual(stockActual);        nuevo.setStockMinimo(stockMinimo);        nuevo.setCategoria(categoria);         listaArticulos.add(nuevo);         JOptionPane.showMessageDialog(this , listaArticulos.toString());    }                                               private void txtCodigoActionPerformed( java.awt .event .ActionEvent  evt) {        // TODO add your handling code here:    }                                               public static void main(String  args[]) {          try {                if ("Nimbus".equals(info.getName())) {                    javax.swing .UIManager .setLookAndFeel( info.getClassName());                    break;                }            }            java.util.logging.Logger.getLogger(AltaArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);            java.util.logging.Logger.getLogger(AltaArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);            java.util.logging.Logger.getLogger(AltaArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);            java.util.logging.Logger.getLogger(AltaArticulo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        }        //</editor-fold>              public void run() {                new AltaArticulo().setVisible(true);            }        });    }     // Variables declaration - do not modify                         private javax.swing .JButton  btnAgregar;    private javax.swing .JLabel  jLabel1;    private javax.swing .JLabel  jLabel2;    private javax.swing .JLabel  jLabel3;    private javax.swing .JLabel  jLabel4;    private javax.swing .JLabel  jLabel5;    private javax.swing .JLabel  jLabel6;    // End of variables declaration                   }  
 Articulo classimport java.util.ArrayList; public class ConsultaArticulos extends  javax.swing .JFrame {      public ConsultaArticulos() {        initComponents();    }     public ConsultaArticulos(ArrayList<Articulo> listaArticulos) {        initComponents();        lstArticulos.setListData(listaArticulos.toArray());    }     private void initComponents() {         lstArticulos = new  javax.swing .JList();          jScrollPane1.setViewportView(lstArticulos);         getContentPane() .add( jScrollPane1, java.awt .BorderLayout .CENTER);         pack();    }// </editor-fold>                              public static void main(String  args[]) {         try {                if ("Nimbus".equals(info.getName())) {                    javax.swing .UIManager .setLookAndFeel( info.getClassName());                    break;                }            }            java.util.logging.Logger.getLogger(ConsultaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);            java.util.logging.Logger.getLogger(ConsultaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);            java.util.logging.Logger.getLogger(ConsultaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);            java.util.logging.Logger.getLogger(ConsultaArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        }        //</editor-fold>              public void run() {                new ConsultaArticulos().setVisible(true);            }        });    }     // Variables declaration - do not modify                         private javax.swing .JList  lstArticulos;    // End of variables declaration                   }  
 public class Articulo {    private int codigo;    private float precio;    private int stockActual;    private int stockMinimo;    private int categoria;     public Articulo() {    }     public int getCodigo() {        return codigo;    }     public void setCodigo(int codigo) {        this.codigo = codigo;    }         return nombre;    }     public void setNombre(String  nombre) {        this.nombre = nombre;    }     public float getPrecio() {        return precio;    }     public void setPrecio(float precio) {        this.precio = precio;    }     public int getStockActual() {        return stockActual;    }     public void setStockActual(int stockActual) {        this.stockActual = stockActual;    }     public int getStockMinimo() {        return stockMinimo;    }     public void setStockMinimo(int stockMinimo) {        this.stockMinimo = stockMinimo;    }     public int getCategoria() {        return categoria;    }     public void setCategoria(int categoria) {        this.categoria = categoria;    }     @Override        return "Articulo{" + "codigo=" + codigo + ", nombre=" + nombre + ", precio=" + precio + ", stockActual=" + stockActual + ", stockMinimo=" + stockMinimo + ", categoria=" + categoria + '}';    } }  
 
 
 |  
						| 
								|  |  
								| « Última modificación: 28 Febrero 2015, 01:29 am por touchi » |  En línea | 
 
 |  |  |  | 
			| 
					
						| 3n31ch 
								 
								
								 Desconectado 
								Mensajes: 445
								
								 
								Grandes conocimientos engendran grandes dudas
								
								
								
								
								
								   | 
 
Podrias poner tu codigo en el foro?
 Modifica tu mensaje, copia y pega el codigo, seleccionalo y luego en el combobox que dice GeSHi selecciona JAVA.
 
 De esta manera sera mas facil acceder a el y ayudarte (Nose los demas, pero a mi no me apetece ponerme a descargar nada)
 
 
 |  
						| 
								|  |  
								|  |  En línea | 
 
 |  |  |  | 
			| 
					
						| touchi 
								
								 Desconectado 
								Mensajes: 8
								
								
								
								
								
								   | 
 
Ahí puse el código, supuse que iba a ser mas organizado ver cada clase separada. Disculpas~ |  
						| 
								|  |  
								|  |  En línea | 
 
 |  |  |  | 
			| 
					
						| robertofd1995 
								
								 Desconectado 
								Mensajes: 172
								
								
								
								
								
								   | 
 
Me parece que tienes una buena liada , a ver para  empezar comentar la clase no seria mala idea , y para seguir que problema tienes al cargar los articulos , le he pegado una vista rapida , pero si lo demas funciona no se que problemas te puede presentar eso .
 Y se un poco mas especifico con tu problema , que es lo que no puedes hacer ?
 
 Y porque extiendes 3 JFrame en las 3 clases? Los JPanel y JDialog estan para algo.
 
 Saludos
 |  
						| 
								|  |  
								|  |  En línea | 
 
 |  |  |  | 
			| 
					
						| 3n31ch 
								 
								
								 Desconectado 
								Mensajes: 445
								
								 
								Grandes conocimientos engendran grandes dudas
								
								
								
								
								
								   | 
 
Lo vi a la rapida, no  lei nada. Por lo que vi, me huele a código autogenerado de Netbeans. Estoy en lo correcto? Por otro lado, es mejor que pongas el extracto en donde tienes el problema, no que pongas todooooo el codigo    |  
						| 
								|  |  
								|  |  En línea | 
 
 |  |  |  | 
			| 
					
						| touchi 
								
								 Desconectado 
								Mensajes: 8
								
								
								
								
								
								   | 
 
Perdon otra vez por el desorden.
 Mi problema es lo que no esta, en realidad lo que necesito saber es como conseguir los valores de los atributos en especifico para responder a lo siguiente.
 
 cantidad de productos de cada tipo.
 total de dinero en artículos.
 porcentaje de artículos de tipo 2.
 Y articulo con el precio mas elevado.
 
 Esta claro que es necesario utilizar un bucle for/ for each, pero no se como obtener esos datos. Si me podes tirar un ejemplo de una nomas de las consignas que puse arriba ya voy a saber por donde agarrar.
 
 sobre lo de los 3 JFrame la verdad es que asi me enseñaron o me están enseñando mejor dicho. Estoy aprendiendo java. Pero la verdad es que no se me da bien programar.
 
 |  
						| 
								|  |  
								|  |  En línea | 
 
 |  |  |  | 
			| 
					
						| touchi 
								
								 Desconectado 
								Mensajes: 8
								
								
								
								
								
								   | 
 
Algunas cosas son auto generadas, digamos los JFrame si son auto generados y lo visual esta echo con el diseñador proporcionado por NetBeans. |  
						| 
								|  |  
								|  |  En línea | 
 
 |  |  |  | 
			| 
					
						| Usuario Invitado 
								 
								
								 Desconectado 
								Mensajes: 625
								
								   | 
 
NOTA: He publicado la respuesta cuando habías puesto el link, por lo que no vi tu actualización hasta ahora.Coloca el código que no cumple su trabajo aquí. Primero porque así ayudará a personas que tengan el mismo problema y segundo, porque casi nadie se tomará la molestia de crear un proyecto y agregar las clases y demás que ha descargado. Por lo que dices aquí supongo que estás trabajando con listas para simular una BBDD, ¿cierto?: cantidad de productos de cada tipo.total de dinero en artículos.
 porcentaje de artículos de tipo 2.
 Y articulo con el precio mas elevado.
 Ok, vamos por partes como dijo Jack el destripador ^^. Primer, creamos un Value Object que representa a un producto: public class ProductVO {     public ProductVO() {}         this.id = id;        this.name = name;        this.description = description;        this.price = price;        this.category = category;    }    /*public ProductVO(Object... data) {                for(byte i=0; i<data.length; i++) {            String curObjectClassName = data[i].getClass().getSimpleName();            switch(curObjectClassName.toLowerCase()) {                case "byte": this.id = (Byte) id;                case "string":                    switch(i) {                        case 1: this.name = (String) data[i]; break;                        case 2: this.username = (String) data[i]; break;                        case 4: this.category = (String) data[i]; break;                    }; break;                case "double": this.price = (Double) price; break;            }        }    }*/     public Integer getId() { return  id; }     public void setId(Integer  id) { this .id =  id; }     public String getName() { return  name; }     public void setName(String  name) { this .name =  name; }     public String getDescription() { return  description; }     public void setDescription(String  description) { this .description =  description; }     public Double getPrice() { return  price; }     public void setPrice(Double  price) { this .price =  price; }     public Integer getCategory() { return  category; }     public void setCategory(Integer  category) { this .category =  category; } }
 Luego, creamos el objeto encargado de manejar las consultas e inicializar la lista: import java.util.Collections;import java.util.List;import java.util.ArrayList;  public class ProductQuery {    private static List<ProductVO> productsList = new ArrayList<>();     static {            new ProductVO(1, "Cepillo Colgate super", "Cepillo de dientes extra duradero", 18.5d, 1),            new ProductVO(2, "Jarabe para tos", "Jarabe para la tos sabor miel", 25.90d, 2),            new ProductVO(3, "Aspirina", "Pastilla para el dolor de cabeza", 4.3d, 2)        );    }     public int[] getProductExistencesByCategory(int category) {        final int SEARCH_ALL = -1;        final int GROOMING_CATEGORY = 1;        final int MEDICINE_CATEGORY = 2;        int groomingCategoryExistences = 0; // cantidad de productos en aseo personal        int medicineCategoryExistences = 0; // cantidad de productos en medicina        int requestCategoryExistences = 0;         for(ProductVO product : productsList) {            if(category != SEARCH_ALL) {                if(product.getCategory() == category) {                    requestCategoryExistences++;                }            } else {                if(product.getCategory() == GROOMING_CATEGORY)                  groomingCategoryExistences++;                if(product.getCategory() == MEDICINE_CATEGORY)                  medicineCategoryExistences++;            }        }        if(category != SEARCH_ALL)            return new int[] { requestCategoryExistences };        else            return new int[] {groomingCategoryExistences, medicineCategoryExistences};        }     public Double getTotalAmountOfProducts() {         for(ProductVO product : productsList) {            totalAmount += product.getPrice();        }        return totalAmount;    }     public ProductVO getMostValuedProduct() {        ProductVO mostValued = productsList.get(0);         for(ProductVO product : productsList) {            if(product.getPrice() > mostValued.getPrice())                mostValued = product;        }         return mostValued;    }  }
 El código entre static {} , se ejecutará cuando el ClassLoader cargue la clase, es decir, se ejecutará de forma simultánea a la compilación. Esto para que la lista de productos esté disponible ni bien ejecutamos la aplicación. Por último, hacemos pruebas: public class ProductsTest{      public static void main(String [] args){        ProductQuery query = new ProductQuery();        int[] categoryExistences = query.getProductExistencesByCategory(-1);        int[] medicineCategoryExistences = query.getProductExistencesByCategory(2);        ProductVO mostValuedProduct = query.getMostValuedProduct();        Double totalAmount =  query.getTotalAmountOfProducts();         System.out .println("Products existences by category: ");        printArray(categoryExistences);        System.out .println("Products existences by medicine category: ");        printArray(medicineCategoryExistences);        System.out .println("Most valued product: "+ mostValuedProduct.getName());        System.out .println("Total amount of products: "+ totalAmount);     }      public static void printArray(int[] array) {       for(int value : array)     } }
 Resutados:
 Products existences by category: 1
 2
 Products existences by medicine category:
 2
 Most valued product: Jarabe para tos
 Total amount of products: 48.699999999999996
Si tienes alguna duda, no dudes en preguntar. |  
						| 
								|  |  
								| « Última modificación: 27 Febrero 2015, 23:00 pm por Gus Garsaky » |  En línea | 
 
 "La vida es muy peligrosa. No por las personas que hacen el mal, si no por las que se sientan a ver lo que pasa." Albert Einstein |  |  |  | 
			| 
					
						| 3n31ch 
								 
								
								 Desconectado 
								Mensajes: 445
								
								 
								Grandes conocimientos engendran grandes dudas
								
								
								
								
								
								   | 
 
Pues nada, estaba escribiéndote el ejemplo pero Gus lo publico antes. Con eso ha de ser suficiente. Suerte ^^
 PD: Un dia de estos hare una campaña para exterminar a todos los profesores que enseñen a programar usando el "diseñador" de netbeans.
 
 
 |  
						| 
								|  |  
								|  |  En línea | 
 
 |  |  |  | 
			| 
					
						| Usuario Invitado 
								 
								
								 Desconectado 
								Mensajes: 625
								
								   | 
 
+1 Nacho. Avísame cuándo es la  campaña xD |  
						| 
								|  |  
								|  |  En línea | 
 
 "La vida es muy peligrosa. No por las personas que hacen el mal, si no por las que se sientan a ver lo que pasa." Albert Einstein |  |  |  |  |  
 
	
 
 
				
					
						| Mensajes similares |  
						|  | Asunto | Iniciado por | Respuestas | Vistas | Último mensaje |  
						|   |   | consulta ciclo for 100.000.000 de datos en un arraylist Java
 | neomadara | 2 | 1,988 |  1 Mayo 2014, 22:04 pm por ivancea96
 |  
						|   |   | ArrayList varios tipos de Objetos Java
 | Winterz | 0 | 1,823 |  28 Mayo 2014, 17:36 pm por Winterz
 |  
						|   |   | ¿Cómo manejar un ArrayList de objetos? Java
 | luchi | 2 | 3,208 |  3 Septiembre 2016, 18:28 pm por luchi
 |  
						|   |   | Obtener datos de un ArrayList [Editado] Java
 | i33naxo | 0 | 2,516 |  12 Diciembre 2016, 23:26 pm por i33naxo
 |  
						|   |   | Ayuda agregando objetos a un ArrayList Java
 | Casvill | 6 | 3,080 |  7 Enero 2019, 21:31 pm por antopixel
 |    |