Search code examples
javaenumsjradiobutton

Can I add a JRadioButton for each value in an enum?


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 JRadioButtons 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?


Solution

  • First of all, be sure to set the JRadioButton's actionCommand String with the diff.name. JRadioButtons don't automatically set their actionCommand String with a constructor parameter String like a JButton will.

    Next, the key question is when will you be querying the JRadioButton for their selection. If it's on button press, then give the JRadioButton an ActionListener or an ItemListener. If it's on press of a "submit" JButton, then get the selected radiobutton's model via your ButtonGroup's getSelection() method. This returns the ButtonModel of the selected JRadioButton, or it returns null if no JRadioButtons have been selected. Then you can get the model's actionCommand via getActionCommand() to see which enum has been selected.