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());
}
}
Only reason i can imagine that you have declared the
resultas some super type list, likeList<?>orList<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:
Update (after problem code added):
Your problem seems be this:
as i suspected.
Try
About
Lists and converting toArrays see more here Convert list to array in Java