我为for
{{1}中的每个值为JRadioButton
ButtonGroup
创建了btgrpDiff
循环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");
}
循环之外的setSelected
ButtonGroup
如何btgrpDiff
?我想在它们全部被选中后直接设置它,或者在我的枚举中为每个难度级别设置一个布尔参数,以确定它们是否在for
循环中被设置为选中,但我是不确定哪个最好,或者确切地获得for
的{{1}}。
答案 0 :(得分:1)
创建后将按钮放在ArrayList中。
作为类变量你应该
ArrayList<JRadioButton> mylist = new ArrayList<JRadioButton>()
所以在循环内部执行:
mylist.add(new JRadioButton(diff.name));
然后您可以随时使用mylist.get(i)
答案 1 :(得分:1)
或者将它们放在地图中,然后您可以直接获取它们:
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);
...
}