Reputation: 151
I have a Proveedores class with ID, Name, Lastname and I want add this object into the combobox.
ListIterator listaNombre = listaProveedores.listIterator();
listado = new Proveedores[listaProveedores.size()];
int cont = 0;
while (listaNombre.hasNext()) {
prov = (Proveedores) listaNombre.next();
listado[cont] = prov;
cont++;
}
this.vista.cArticuloFamilia.setModel(new javax.swing.DefaultComboBoxModel(listado));
With this code I add the differents objects into the combobox. It works. But now I want to override the toString method for show only Name attribute. Now combobox shows me the name class (Proveedores) and the ID.
entidades.Proveedores[idProveedores=1]
How can I override it to show the Proveedores Name?
Thanks.
Upvotes: 5
Views: 4910
Reputation: 897
Java uses toString() to get the String representation of the Object by default it will return fully qualified classname @ followed by hashCode of the object.
Use ListCellRenderer to display Proveedores Name in the ComboBox.
Sample Code:
public static class ProveedoresRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus ) {
Object item = value;
// if the item to be rendered is Proveedores then display it's Name
if( item instanceof Proveedores ) {
item = ( ( Proveedores ) item ).getName();
}
return super.getListCellRendererComponent( list, item, index, isSelected, cellHasFocus);
}
}
then set the ProveedoresRenderer to the JComboBox.
ListIterator listaNombre = listaProveedores.listIterator();
listado = new Proveedores[listaProveedores.size()];
int cont = 0;
while (listaNombre.hasNext()) {
prov = (Proveedores) listaNombre.next();
listado[cont] = prov;
cont++;
}
this.vista.cArticuloFamilia.setModel(new javax.swing.DefaultComboBoxModel(listado));
// Set custom renderer to the combobox
this.vista.cArticuloFamilia.setRenderer( new ProveedoresRenderer() );
Upvotes: 10
Reputation: 24262
Use a custom ListCellRenderer to accomplish this.
You shouldn't tailor toString() to produce GUI data for complex objects. It is meant for an internal data representation for the developers eyes, not the users.
Upvotes: 9