Put array of objects in comboBox

2

I have the following method to add objects to a JComboBox :

public void PopulaCategoria() throws SQLException{
    for(Categoria categoria : caDAO.getCategorias()){
        comboCategoria.addItem(categoria);
    }              
}

But the error in comboCategoria.addItem(categoria); saying that Categoria can not be converted to String , however I already put toString() method inside my Categoria model:

@Override
public String toString(){
    return this.nomCategoria;
}

Should not it add objects within JComboBox and show only the name?

    
asked by anonymous 04.05.2018 / 18:54

1 answer

2

It's not just because there is a toString() method that means that it would be called automagically. You should call it:

public void PopulaCategoria() throws SQLException{
    for(Categoria categoria : caDAO.getCategorias()){
        comboCategoria.addItem(categoria.toString());
    }              
}

There are some places in the API that even look like it would be called automagically. What happens is that some methods are given the type Object (this is not the case for this addItem ), and then, within the implementation of this method, toString() is called.

In this case, the parameter type of addItem is <E> , ie it is a generic method. If you have JComboBox<String> , then the parameter type will be String . You can do the addition directly if you have a JComboBox<Categoria> or a JComboBox<? super Categoria> .

    
04.05.2018 / 19:07