Search code examples
javaswingjcombobox

Modify toString() method JComboBox Swing


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.


Solution

  • 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.