1

I've built a combobox that is dynamically populated depending on the contents of another combobox, and so on. I've decided, although it's a bit terrible, to experiment with iterating through the contents of the source array when populating the target combobox. However, although this results in combobox contents, they are repeated. I've stepped through the code, and the array is only being iterated through once.

 private JComboBox regBuildingSelectBox;
...
 String[] siteSelectStrings = {"Site", "London", "Long Island"};
    JComboBox regSiteSelectBox = new JComboBox(siteSelectStrings);
    regSiteSelectBox.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent arg0) {
            getDropDownVariables gddv = new getDropDownVariables();
            for(String s:
                   gddv.buildingSelectList
                            (regSiteSelectBox.getSelectedItem().toString()))
            {
                regBuildingSelectBox.addItem(s);
            }
        }
    });
    regSiteSelectBox.setBounds(24, 336, 282, 20);
    contentPane.add(regSiteSelectBox);


    regBuildingSelectBox = new JComboBox();

    regBuildingSelectBox.setBounds(24, 367, 282, 20);
    contentPane.add(regBuildingSelectBox);

The code containing the arrays is as follows:

public class getDropDownVariables {

    public String[] buildingSelectList(String site)
    {
        switch (site)
        {
        case "London":
            return new String[]  {"Building", "Harvell", 
                                "LYNX Complex", "Caroline", "Salters"};
        case "Long Island":
            return new String[] {"Building", "Phillips", "Pascal"};
        }
        return new String[] {"Failed to populate buildings"};
    }

And the result:

enter image description here

Wolfish
  • 960
  • 2
  • 8
  • 34
  • It may only loop once, but how many times is the event firing? You should just clear the combo box prior to adding items. (also, if the event is firing multiple times you might need to address that problem separately anyway) – musefan Dec 05 '16 at 14:41
  • @musefan Yes, this is correct - however it is seemingly unrelated, as adding an if clause for an already-populated combobox does not change the result. – Wolfish Dec 05 '16 at 14:43
  • @Berger wow... really? That's weird... thanks for that link – Wolfish Dec 05 '16 at 14:43
  • @Wolfish : The problem is that you get an event for the selected item, and another one for the deselected item . – Arnaud Dec 05 '16 at 14:47
  • @Berger Yep... that's mildly infuriating. – Wolfish Dec 05 '16 at 15:00

1 Answers1

0

Just a guess, but before you call regBuildingSelectBox.addItem(s); you probably have to clear it first, otherwise it just keeps adding to the list rather than replacing it. There allso might be a different method that sets the values vs adding.

Brian Pipa
  • 808
  • 9
  • 23