If I have the following 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;
}
}
And I have a Choice
that I want to add each of Difficulty
's value to:
for (Difficulty diff : Difficulty.values()) {
choiceDiff.add(diff.name);
}
and I add an ItemListener
:
choiceDiff.addItemListener((ItemEvent e) -> {
labDifficulty.setText("High Score for " + choiceDiff.getSelectedItem() + " Difficulty:");
labDifficultyScore.setText(Integer.toString(HIGH_SCORES[choiceDiff.getSelectedIndex()]));
}
Now, if I wanted to have a few JRadioButton
s instead of a Choice
; is there any way to do this in a similar way to what I have above? I want to be able to alter the difficulty levels and their information (they'll have more attributes than just a name when fully-implemented) while avoiding repetition and having the enum
as a central point to make any changes to the difficulties.
I'd like to do something like this (ignoring for now that EXTRA_HARD
's name
has a space in it):
ButtonGroup btgrpDiff = new ButtonGroup();
for (Difficulty diff : Difficulty.values()) {
String name = diff.name;
JRadioButton name = new JRadioButton(diff.name);
name.addItemListener((ItemEvent e) -> {
labDifficulty.setText("High Score for " + diff.name + " Difficulty:");
labDifficultyScore.setText(Integer.toString(HIGH_SCORES[diff.ordinal()]));
}
btgrpDiff.add(name);
}
Is there any way of making this work, or is there some other way that would bring about the same result?