How to get the selected radio button from ToggleGroup

I am working on JavaFX 8 and SceneBuilder . I created some radio buttons in the FXML file and specified the name toggleGroup in the list of radio buttons. So, now I want to get the toggleGroup switch in my controller, I need to make all the radio buttons again as fields in the controller, or just the toggleGroup object will get me the selected switch (the text of this switch, not the button object).

+12
source share
3 answers
  @FXML ToggleGroup right; //I called it right in SceneBuilder. 

later somewhere in the method.

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

Let's say you have a switch group and three switches belonging to this 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 this switch group, the following changed(...) method is 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 } } }); 
+14
source

It never answered properly or carefully, so I decided to post the solution I received.

When creating radio buttons in SceneBuilder , then use SceneBuilder to assign them to the group. The way to access this group through the controller is to first create a variable of type ToggleGroup in the controller and call it the same name as the one you created in SceneBuilder . Then you can use it. Here is an example of pseudo code as 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 long. Here's how to get 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 along the way ...

+9
source

All Articles