Place object array in combobox

Asked

Viewed 257 times

2

I have the following method for adding objects to a JComboBox:

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

But he made a mistake in comboCategoria.addItem(categoria); saying that Categoria cannot be converted into String, but I’ve already put the method toString() inside my model Categoria:

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

He shouldn’t add the objects inside the JComboBox and show only the name?

1 answer

2

It’s not just because there’s a method toString() that means 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 it would appear to be called automagically. What happens is that some methods take the type as a parameter Object (this is not the case addItem), And then, within the implementation of this method, the toString() is called.

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

  • So if I want to insert an object in the combobox I will have to use another method?

  • @Eduardobalestrin Where and how this JComboBox is declared?

  • Previously it was like this private javax.swing.Jcombobox<String> comboCategoria; -> Now that I saw the String I changed to: private javax.swing.Jcombobox<Category> comboCategoria;. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.