How to get selected radio button from ToggleGroup

Let's say you have a toggle group and three radio buttons belonging to that group.

ToggleGroup group = new ToggleGroup();

RadioButton rb1 = new RadioButton("RadioButton1");
rb1.setUserData("RadioButton1");
rb1.setToggleGroup(group);
rb1.setSelected(true);

RadioButton rb2 = new RadioButton("RadioButton2");
rb2.setUserData("RadioButton2");
rb2.setToggleGroup(group);

RadioButton rb3 = new RadioButton("RadioButton3");
rb3.setUserData("RadioButton3");
rb3.setToggleGroup(group);

When you select a radio button from that toggle group, the following changed(...) method will be called.

group.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){
    public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) {

         if (group.getSelectedToggle() != null) {

             System.out.println(group.getSelectedToggle().getUserData().toString());
             // Do something here with the userData of newly selected radioButton

         }

     } 
});

 @FXML
 ToggleGroup right; //I called it right in SceneBuilder.

later somewhere in method.

RadioButton selectedRadioButton = (RadioButton) right.getSelectedToggle();
String toogleGroupValue = selectedRadioButton.getText();

This was never properly or thoroughly answered, so I thought I would post the solution I got.

When you create radio buttons in SceneBuilder, then ALSO use SceneBuilder to assign them to a group. The way you access that group via the Controller is to first create a variable of type ToggleGroup in the Controller and name it the exact same name as the one you created in SceneBuilder. Then you can use it. Here is a pseudocode example of how I did it:

// your imports
public class Controller
{
    @FXML ToggleGroup   myGroup; //I called it myGroup in SceneBuilder as well.

    public void myGroupAction(ActionEvent action)
    {
      System.out.println("Toggled: " + myGroup.getSelectedToggle().getUserData().toString());
    }

    public void initialize()
    {
      //whatever initialize code you have here
    }
}

Although the text returned from the getUserData property is lengthy. Here is a way to get just the name of the Radio Button:

myGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
    {
    @Override
    public void changed(ObservableValue<? extends Toggle> ov, Toggle t, Toggle t1)
        {
        RadioButton chk = (RadioButton)t1.getToggleGroup().getSelectedToggle(); // Cast object to radio button
        System.out.println("Selected Radio Button - "+chk.getText());
        }
    });

Hope this helps someone down the road ...

Tags:

Javafx

Fxml