Search code examples
javaarraysdatabasejpaobjectdb

Populating JComboBox with TypedQuery<Entity> does not show Entitys name correct


I want get the name of each object in this return list, but the output is an array of Object[], and this show entitys.Categoria[id=1] in my JComboBox control.

I not understand this. Please help me! This is my code:

public List<Categoria> consultarCategorias() {
    try {            
        TypedQuery<Categoria> q = 
                em.createQuery("select c from Categoria c", Categoria.class);
            List<Categoria> results = q.getResultList();            
            return results;
    } catch (Exception e) {
        return null;
    }
}

Note: I use this

for (Categoria c : results) {
   System.out.println(c.getName());
}    

and not work, this show the result cannot convert to Categoria

This is the code to fill my JComboBox:

public void fillCmbCategorias() {
   cmbCategoria.removeAllItems();
   try {
      Object[] listaCategorias = crud.consultarCategorias().toArray();
      DefaultComboBoxModel dcb = new DefaultComboBoxModel(listaCategorias);
      cmbCategoria.setModel(dcb);
   } catch (Exception e) {
      JOptionPane.showMessageDialog(null
              ,"No se pudo cargar la lista de categorias. " + e.getMessage());
   }
}

Solution

  • Only reason i can imagine that you have declared the result as some super type list, like List<?> or List<Object>.

    Assuming you can assing the return value of consultarCategorias() to it.

    And of course you should not do it this way - you should correct the list generic type - but this might then work:

    for (Object c : results) {
       System.out.println(((Categoria)c).getName());
    }
    

    Update (after problem code added):

    Your problem seems be this:

    Object[] listaCategorias = crud.consultarCategorias().toArray();
    

    as i suspected.

    Try

    Categoria[] listaCategorias =
       crud.consultarCategorias().toArray(new Categoria[]{});
    // toArray() needs some array instance to determine the type
    

    About Lists and converting to Arrays see more here Convert list to array in Java