0

I've got the following for loop creating JRadioButtons for the ButtonGroup btgrpDiff for each of the values in my Difficulty enum:

private enum Difficulty {
    EASY("Easy"),
    MEDIUM("Medium"),
    HARD("Hard"),
    EXTRA_HARD("Extra Hard");

    public final String name;

    private Difficulty(String name) {
        this.name = name;
    }
}

for (Difficulty diff : Difficulty.values()) {
    JRadioButton radDiff = new JRadioButton(diff.name);
    radDiff.setActionCommand(diff.name);
    btgrpDiff.add(radDiff);
    panDiff.add(radDiff, "align 50%, shrink 2, wrap");
}

How can I setSelected for the ButtonGroup btgrpDiff outside of the for loop? I'd like to either set it straight after they're all selected or have a boolean parameter for each difficulty level in my enum to determine whether or not they get set as selected in the for loop, but I'm not sure which would be best, or how exactly to get the ButtonModel for the JRadioButtons.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
DagdA
  • 484
  • 1
  • 7
  • 25
  • 1
    on creation throw them in a list, then you can iterate through the list running the method on all buttons you want – Bart Hofma Dec 18 '14 at 15:49

2 Answers2

1

Upon creation put your buttons in an ArrayList.

as class variable you should have

ArrayList<JRadioButton> mylist = new ArrayList<JRadioButton>()

So inside the loop do:

mylist.add(new JRadioButton(diff.name));

then you can access them anytime you want using mylist.get(i)

Bart Hofma
  • 644
  • 5
  • 19
1

Or put them in a Map, then you can get them directly:

Map<Difficulty,JRadioButton> rButtons = new HashMap<Difficulty,JRadioButton>();

for (Difficulty diff : Difficulty.values()) {
  JRadioButton radDiff = new JRadioButton(diff.name);
  rButtons.put(diff,radDiff);
  btgrpDiff.add(radDiff);
...
}
Bday
  • 1,005
  • 7
  • 13