mercredi 22 février 2017

Can I add a JComboBox within an if statement?

I'm trying to build a GUI for my first program that uses a set of related objects that may or may not contain subsequent choices. So the user must use a combo box to select their first option and if the first option has further refinement it is supposed to add a second JComboBox that is populated with those choices.

The code I use to do this is listed here:

public static void selectRace(GUI e){
    //Divides the window into four sections
    GridLayout raceDivider = new GridLayout(1,4,0,0);
    //Manages the set layout for the first section
    FlowLayout selectionLayout = new FlowLayout(FlowLayout.CENTER, 0 , 0);
    e.setLayout(raceDivider);
    JPanel selection = new JPanel();
    selection.setLayout(selectionLayout);
    JComboBox race = new JComboBox();
    JComboBox subrace = new JComboBox();
    //Populate and add the first combobox with the data contained in the Race class
    for(String a : Race.races.keySet()){
        race.addItem(Race.races.get(a));
    }
    selection.add(race);
    race.addItemListener(new ItemListener(){
        @Override
        public void itemStateChanged(ItemEvent event){
            //If the second combobox was there in the first place with other options remove it
            selection.remove(subrace);
            //If an item was selected populate the second combobox with all of the possible secondary options
            if(event.getStateChange() == 1){
                Race selected = (Race)race.getSelectedItem();
                if(!(selected.subraces.isEmpty())){
                    subrace.removeAll();
                    for(String b : selected.subraces.keySet()){
                        subrace.addItem(selected.subraces.get(b));
                    }
                }
            }
            System.out.println(subrace.getItemCount());
            //If the second combobox has any secondary options in it, add it back to the JPanel
            if(subrace.getItemCount() > 0){
                selection.add(subrace);
            }
        }
    });
    e.add(selection);
    e.setVisible(true);
}

I have inserted code to ensure that the item count is greater than 0 and even have added println commands above and below the selection.add(subrace) line and they print but for some reason the JComboBox won't appear on the JPanel. If I move the statement outside of the if statement it shows up no problem.

Is there something I'm missing or do I need to repaint the window or something else?

BTW this is for a DnD creation tool

Aucun commentaire:

Enregistrer un commentaire