Reputation: 77
I want to fill a JComboBox using a DefaultComboBoxModel.
static JComboBox<Carta> cmb_cartas;
static DefaultComboBoxModel<Carta> mdl_cartas;
I fill the DefaultComboBoxModel with an ArrayList of my own class "Carta"
ArrayList<Carta> cartas = conOAD.getCartasPorAgregar(idConjunto);
mdl_cartas = new DefaultComboBoxModel<Carta>();
for(int i = 0; i < cartas.size(); i++) {
Carta carta = cartas.get(i);
mdl_cartas.addElement(carta);
}
cmb_cartas = new JComboBox<>(mdl_cartas);
The combobox is filled correctly but the problem is that the text of the options are displaying: "modelos.Carta@3e7e084e"
How can is set the text to be the attribute "nombre" of my class "Carta"?
Upvotes: 0
Views: 127
Reputation: 69339
You could override the toString
method for your Carta
class.
@Override
public String toString() {
return this.nombre; // assumes nombre is a string
}
However, many people (rightly) frown on abusing the toString
method for GUI display purposes. You could instead create a custom ListCellRenderer
to render the text you want for each object.
Upvotes: 3