Move data from one JComboBox to another JComboBox

0

I want to do exactly that, I have a list and if I select an element in JComboBox a is added to JComboBox b , it happens that when the add occurs in JComboBox b the event is launched and returns the element to me JComboBox a .

Here is an MVCE to check it (if you comment the listener B you will see that it works correctly):

public static void main(String[] args) {
    String[] lenguages = new String[] {"Java", "C++", "Pearl", "Python", "Bash", "Basic", "Cobol", "Haskell", ".NET", "Pascal"};

    final JPanel panel = new JPanel();
    final JFrame frame = new JFrame();
    final JComboBox<String> comboA = new JComboBox<String>(lenguages);
    final JComboBox<String> comboB = new JComboBox<String>();
    comboA.setPreferredSize(new Dimension(210, 30));
    comboB.setPreferredSize(new Dimension(210, 30));

    comboA.addActionListener (new ActionListener () {
        public void actionPerformed(ActionEvent e) {

            // recuperamos el elemento seleccionado y  lo pasamos al otro combo 
            String elementoSeleccionado = (String) comboA.getSelectedItem();
            System.out.println("A>" + elementoSeleccionado);

            // lo pasamos al otro combo
            comboB.addItem(elementoSeleccionado);

            // y lo eliminamos
            comboA.removeItem(elementoSeleccionado);
        }
    });

    comboB.addActionListener (new ActionListener () {
        public void actionPerformed(ActionEvent e) {

            // recuperamos el elemento seleccionado y  lo pasamos al otro combo 
            String elementoSeleccionado = (String) comboB.getSelectedItem();
            System.out.println("B>" + elementoSeleccionado);

            // lo pasamos al otro combo
            comboA.addItem(elementoSeleccionado);

            // y lo eliminamos
            comboB.removeItem(elementoSeleccionado);
        }
    });

    // contenedor para los jcombobox
    panel.add(comboA);
    panel.add(comboB);

    // frame principal
    JFrame.setDefaultLookAndFeelDecorated(true);
    frame.setSize(500, 100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.setVisible(true);
}

RESULT (always combo B empty)

A>Cobol
B>Cobol
A>Cobol
B>Cobol
A>Bash
B>Bash
A>.NET
B>.NET
    
asked by Jordi Castilla 20.07.2016 в 13:19
source

1 answer

-1

I think I understand what you want to do, I did something similar with this help link

Greetings !!

    
answered by 26.07.2016 в 00:07