Add first item to Jcombobox

Asked

Viewed 21 times

0

I’m filling my Jcombobox like this:

 private void preencherCombo(  ){        
        jComboEstado.removeAllItems();        
        List<Estado> lista = ec.listaObj("");        
       jComboEstado.addItem("Selecione um estado");        
        for( Estado e: lista ){
            jComboEstado.addItem(e);
        }
    }

I’m trying to read the selected combobox option like this:

Estado e = (Estado) jComboEstado.getSelectedItem();

My Jcombobox is declared so:

 private javax.swing.JComboBox jComboEstado;

I would like to add the first Item:

jComboEstado.addItem("Selecione um estado");  

But you’re giving me this problem

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to br.com.brito.pdv.model.Estado

1 answer

0

Apparently you have somehow set jCombo to accept only "State".... then your String cannot be "casted" (nen know if that word exists, but now it has existed) to "State".. When I manipulate values with jCombo I simply leave it to the natural as it came to the world and add String’s in it and not Classes... then to retrieve the selected item I do a comparison and capture the same...

Or create a state with that name and try to add as a first option....

Browser other questions tagged

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