Using JavaFX RadioButtons with an enum

Couldn’t find any good info on this online so posting it here. The goal is to use JavaFX radio buttons with an enum type. Enums (enumerated types) are typically used to define a fixed set of categories which don’t change. For this example I’ve created an enum AccountType which defines different types of bank accounts.

public enum AccountType {
    CHK("Checking"),
    SAV("Savings"),
    CRD("Credit"),
    LON("Loan");

    private String description;

    AccountType(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }
}

Below are the radio buttons which are assigned to the toggle group acctTG. Use the setUserData() method of each radio button to set its UserData property to a particular AccountType. Each radio button’s text is provided by the AccountType getDescription() method.

        acctTG = new ToggleGroup();
        savRB = new RadioButton(AccountType.SAV.getDescription());
        savRB.setUserData(AccountType.SAV);
        savRB.setToggleGroup(acctTG);
        //savRB.setSelected(false);
        chkRB = new RadioButton(AccountType.CHK.getDescription());
        chkRB.setUserData(AccountType.CHK);
        chkRB.setToggleGroup(acctTG);
        crdRB = new RadioButton(AccountType.CRD.getDescription());
        crdRB.setUserData(AccountType.CRD);
        crdRB.setToggleGroup(acctTG);
        lonRB = new RadioButton(AccountType.LON.getDescription());
        lonRB.setUserData(AccountType.LON);
        lonRB.setToggleGroup(acctTG);

And here is a method that returns the AccountType enum from the toggle group:

public AccountType getAccountType() {
        return (AccountType) acctTG.getSelectedToggle().getUserData();
}

getUserData() returns type Object and therefore must be cast to AccountType.