Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected radio button from ToggleGroup

Tags:

javafx

fxml

I an working on JavaFX 8 and SceneBuilder. I created some radio buttons in the FXML File and specified a toggleGroup name to a radio button list in that. So, now I want to get the toggleGroup's selected radio button in my controller, do I need to make all the radio buttons again as fields in the controller, or just the toggleGroup object will get me the selected radio button (the text of that radio button only, not the button object).

like image 223
rjalfa Avatar asked Sep 06 '15 15:09

rjalfa


People also ask

How do I group radio buttons in SceneBuilder?

When you have created a ToggleButton you can select it in SceneBuilder. Then you will find a field on the right side within the inspector named "Toggle Group". Add a name there and SceneBuilder will put the ToggleButton together with all other ToggleButtons which you give the same group name into a ToggleGroup.

What is a radio button selection?

Radio buttons are used when there is a list of two or more options that are mutually exclusive and the user must select exactly one choice.

How do I toggle radio button in Android?

If you are only using one radio box for checking on and off, maybe you should use checkbox or toggle button instead. Scroll down and see checkbox and toggle button. When using radios you usually have more than one and choose between them.


2 Answers

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

later somewhere in method.

RadioButton selectedRadioButton = (RadioButton) right.getSelectedToggle(); String toogleGroupValue = selectedRadioButton.getText(); 
like image 107
Jakub S. Avatar answered Nov 12 '22 17:11

Jakub S.


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           }       }  }); 
like image 35
Ugurcan Yildirim Avatar answered Nov 12 '22 18:11

Ugurcan Yildirim