JComboBox update from another JComboBox

1

My idea was to make a JComboBox whose values were updated according to the options of the previous ComboBox.

I'm using multiple ArrayLists.

For example, a ComboBox with the option of January and February ... If you choose January in the first ComboBox, the second will only have January events.

My screen:

    
asked by anonymous 17.06.2014 / 11:06

3 answers

2

Without your code to help it becomes a bit difficult to help.

Your%% of choice is fixed, that is, do you know what the element of each item is?

However, I'm going to post some sort of Pseudocode to see if it helps. (I'm thinking that your% of choice is fixed)

switch (comboBox1.getSelectItem) {
            case cao:
                    comboBox2.removeAllItens();
                    for(Raça raça: Raças){
                        comboBox2.addItem("raça");
                    }                
                break;
            case ave:
                comboBox2.removeAllItens();
                    for(TipoPassaraos passaro: Passaros){
                        comboBox2.addItem("passaro");
                    }
                break;

}
    
17.07.2014 / 18:56
1

You can use a Listener in the first ComboBox to change the contents of the second. Something like this:

private void configuraComboBox(){
    List<String> meses = Arrays.asList("Janeiro","Fevereiro");
    jCombobox.setModel(new DefaultComboBoxModel(meses.toArray()));

    jCombobox.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {

               if(jCombobox.getSelectedItem() == null){
                  jCombobox2.setModel(new DefaultComboBoxModel<>());

               }else{
                 switch ((String)  jComboBox.getSelectedItem()) {
                    case "Janeiro":
                        jCombobox2.setModel(new DefaultComboBoxModel<String>(getEventosJaneiro()));
                        break;
                    case "Fevereiro":
                        jCombobox2.setModel(new DefaultComboBoxModel<String>(getEventosFevereiro()));
                        break;
                    default:
                       jCombobox2.setModel(new DefaultComboBoxModel<>());
                }
              }
            }
        });
}

private String[] getEventosJaneiro(){
    return new String[]{"Férias", "Atividade"};
}

private String[] getEventosFevereiro(){
    return  new String[]{"Carnaval", "Volta as aulas"};
}
    
15.12.2015 / 15:11
0

You need to use insertion of items at runtime, so use the addItem method. To get clearer:

if(comboBox1.getSelectItem.toString.equals("Frutas"){
comboBox2.addItem("Maçã");
comboBox2.addItem("Pera");
}

To remove:

comboBox1.removeAllItens();

For better clarification: link

    
17.06.2014 / 16:09