How to have two JComboBox with the same elements?

1.5k Views Asked by At

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?

2

There are 2 best solutions below

0
PhoneixS On BEST ANSWER

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).

1
mKorbel On
wrong suggestion start

.

  • How to have two JComboBox with the same elements? --> doesn't make me sence, don't do that, to create only one DefaultComboBoxModel for all JComboBoxes in current JVM, and to share this model for both JComboBoxes

  • it should be inefficient to hold two model, if they contains the same data

  • could be important for editable JComboBox based on AbstractListMode

.

wrong suggestion ended

EDIT intererting event from ListDataListener that sharing selected item for both instances (JComboBox), here is short explanation in SSCCE/MCVE form (see difference between selection for pairs comboBox1 & comboBox2 (uses the simple override for ListDataListener) versus comboBox3 & comboBox4)

.

enter image description here

.

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class SharedDataBetweenComboBoxSample {

    private final String labels[] = {"A", "B", "C", "D", "E", "F", "G"};
    private final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);
    private JFrame frame = new JFrame("Shared Data");
    private JButton button = new JButton("Add");
    private JPanel panel = new JPanel(new GridLayout(2, 0, 10, 10));
    private JComboBox comboBox1 = new JComboBox(new MyComboBoxModel(model));
    private JComboBox comboBox2 = new JComboBox(new MyComboBoxModel(model));
    private JComboBox comboBox3 = new JComboBox((model));
    private JComboBox comboBox4 = new JComboBox((model));

    public SharedDataBetweenComboBoxSample() {
        comboBox1.setPrototypeDisplayValue("New Added");
        //works for editable JComboBox too
        //comboBox1.setEditable(true);
        //comboBox2.setEditable(true);
        panel.add(comboBox1);
        panel.add(comboBox2);
        panel.add(comboBox3);
        panel.add(comboBox4);
        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                model.addElement("New Added");
            }
        };
        button.addActionListener(actionListener);
        frame.add(panel, BorderLayout.NORTH);
        frame.add(button, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    public static class MyComboBoxModel extends DefaultComboBoxModel
           implements ComboBoxModel, ListDataListener {

        private DefaultComboBoxModel original;

        public MyComboBoxModel(DefaultComboBoxModel original) {
            super();
            this.original = original;
        }

        @Override
        public int getSize() {
            return original.getSize();
        }

        @Override
        public Object getElementAt(int index) {
            return original.getElementAt(index);
        }

        @Override
        public void addListDataListener(ListDataListener l) {
            if (getListDataListeners().length == 0) {
                original.addListDataListener(this);
            }
            super.addListDataListener(l);
        }

        @Override
        public void removeListDataListener(ListDataListener l) {
            super.removeListDataListener(l);
            if (getListDataListeners().length == 0) {
                original.removeListDataListener(this);
            }
        }

        @Override
        public void addElement(Object anObject) {
            original.addElement(anObject);
        }

        @Override
        public void removeElement(Object anObject) {
            original.removeElement(anObject);
        }

        @Override
        public int getIndexOf(Object anObject) {
            return original.getIndexOf(anObject);
        }

        @Override
        public void insertElementAt(Object anObject, int index) {
            original.insertElementAt(anObject, index);
        }

        @Override
        public void removeAllElements() {
            original.removeAllElements();
        }

        @Override
        public void removeElementAt(int index) {
            original.removeElementAt(index);
        }

        @Override
        public void intervalAdded(ListDataEvent e) {
            fireIntervalAdded(this, e.getIndex0(), e.getIndex1());
        }

        @Override
        public void intervalRemoved(ListDataEvent e) {
            fireIntervalRemoved(this, e.getIndex0(), e.getIndex1());
        }

        @Override
        public void contentsChanged(ListDataEvent e) {
            fireContentsChanged(this, e.getIndex0(), e.getIndex1());
        }
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SharedDataBetweenComboBoxSample();
            }
        });
    }
}