javaswingclonejcomboboxcomboboxmodel

How to have two JComboBox with the same elements?


I have a list (ArrayList) with elements that I want to show in two JComboBox so both of them show the same elements but when you choose some elements in one JComboBox the other one must not change.

What I do now is to create two DefaultComboBoxModel and add the elements in both in a loop.

DefaultComboBoxModel modeloA = new DefaultComboBoxModel();
DefaultComboBoxModel modeloB = new DefaultComboBoxModel();

// Agregamos el resto de plantillas.
for (OcupacionType plantilla : plantillas) {

    modeloA.addElement(plantilla);
    modeloB.addElement(plantilla);

}

comboboxA.setModel(modeloA);
comboboxB.setModel(modeloB);

Is this the more efficient way to do it? Is it a way to clone the model?


Solution

  • As suggested by @StanislavL in a comment, you can use a Vector to initialize the new models.

    Vector vec = new Vector(plantillas);
    
    comboboxA.setModel(new DefaultComboBoxModel(vec));
    comboboxB.setModel(new DefaultComboBoxModel(vec));
    

    That is very simple and efficient as only made one copy of the elements (to make the vector).