Get Id from an object in the combobox

2

In a Frame for car registration, I have a combobox1 with car brands and another combobox2 with the models, when I choose a brand in CB1 only appear in CB2 the models related to that brand. Tags and templates are bank tables, which are used by a Cars table

 MARCAS
    idMarca
    nome

 MODELOS
    idModelo
    idMarca
    nome

CARROS
    idCarro
    placa
    idMarca
    idmodelo   

I get the two CB's popular in the right way by searching the bank's data and switching to ArrayList's

public void preencherMarcas(){
   MarcasControle marcasControle = new MarcasControle();
   jComboBox1.removeAllItems();

    ArrayList<MarcasModelo> vetorMarcas = new ArrayList();  
    vetorMarcas = marcasControle.preencherMarcas();
    for (MarcasModelo marcas : vetorMarcas) {
         jComboBox1.addItem(marcas.getNome());
         }  
    }

    public void preencherModelos(){
    ModelosControle modelosControle = new ModelosControle();
    jComboBox2.removeAllItems();  
    ArrayList<ModelosModelo> vetorModelos = new ArrayList();  
    vetorModelos = modelosControle.preencherModelos(id);
        for (ModelosModelo modelos : vetorModelos) {
           jComboBox2.addItem(modelos.getNome());
        } 
     }   

But to persist the data I need to know the IdMarge item selected in combobox1 and the idModel of the selected item in combobox2. So my problem is, I can not close this reasoning on how to do this. How to get this information (idMarca and idModelo) of the combombox's. I tried the form below, but it did not work, it presented the error

Marcas mm = (Marcas)jComboBox1.getSelectedItem();
int idMarcas = m.getId();  
  

java.lang.String can not be cast to model.Marks

    
asked by anonymous 15.08.2018 / 20:53

1 answer

3

The error occurs because you are populating the combobox with a set of strings and not with objects of type Marcas , as can be seen in its own code:

ArrayList<MarcasModelo> vetorMarcas = new ArrayList();  
vetorMarcas = marcasControle.preencherMarcas();
for (MarcasModelo marcas : vetorMarcas) {
     jComboBox1.addItem(marcas.getNome());
     }  
}

There is no way to cast String to your object, java does not know how to do this. Or you set the comb to receive only objects of type Marcas (which will probably dispense with the cast) or change the way you are treating the selected item, as a string and without cast, and formulate another way of searching the id of the brand selected in the combobox.

If you choose the combobox with its object, the following links have solutions that explain some ways to do this.

15.08.2018 / 20:58