tigu
tigu

Reputation: 751

How to set Labels of RadioButtonGroup with bound Enum

I have a RadioButtonGroup<MyEnum> and I set the items with an Enum. The labels of the single items are now the elements of my Enum. Because of code conventions, my Enum elements are written big. I added a public String getText(MyEnum e) method to my Enum and I want the labels of the RadioButtonGroup to be these texts.

I also have several ComboBoxes and their elements come from Enums, too. The ComboBoxes have a method setItemLabelGenerator() which I can use to set my Enum elements text presentations as labels.

My Enum

public enum MyEnum{
    OPT1, OPT2, OPT3;

    public static String getText(MyEnum e) {
        switch(e) {
            case OPT1:  return "Option 1";
            case OPT2:  return "Option 2";
            case OPT3:  return "Option 3";
        }
        return "";
    }

    public static Collection<MyEnum > getValues(){
        Collection<MyEnum > resultList = new ArrayList<MyEnum >();
        resultList.add(OPT1);
        resultList.add(OPT2);
        resultList.add(OPT3);
    }
}

In my UI class, I have my RadioButtonGroup with the Enum elements as items:

RadioButtonGroup<MyEnum> myRadioGroup= new RadioButtonGroup<MyEnum>();
myRadioGroup.setItems(MyEnum.getValues());

Unfortunately, the labels of the items are "OPT1", "OPT2" and "OPT3" but I would like them to be "Option 1", "Option 2" and "Option 3".

For my ComboBoxes I can use setItemLabelGenerator() method to get nice labels:

ComboBox<MyEnum> myBox= new ComboBox<MyEnum>();
myBox.setItems(MyEnum.getValues());
myBox.setItemLabelGenerator(MyEnum::getText);

The iteams inmy ComboBox are then "Option 1", "Option 2" and "Option 3".

Can someone tell me, how to get a result like with the ComboBoxes for RadioButtonGroups? I want my users to see nice labels in the UI :-)

Upvotes: 0

Views: 369

Answers (2)

Erik Lumme
Erik Lumme

Reputation: 5342

RadioButtonGroup does not have setItemLabelGenerator(...), but you can achieve the same with setRenderer(new TextRenderer<>(...)).

So in this case

myBox.setRenderer(new TextRenderer<>(MyEnum::getText));

Upvotes: 3

ansjob
ansjob

Reputation: 175

The default behaviour is to do toString on the objects in a ComboBox. So why not make toString return what you expect, or set a label property with a getter?

enum MyOptions {
    OPT1("Option 1"),
    OPT2("Option 2"),
    OPT3("Option 3");

    private final String label;

    MyOptions(String label) {
        this.label = label;
    }

    // either use getLabel as your item label generator...
    public String getLabel() {
        return this.label;
    }

    // ...or if you don't care about printing in logs etc. 
    //    just override the default toString implementation
    public String toString() {
        return this.label;
    }
}

Upvotes: 2

Related Questions