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).
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.
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.
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.
@FXML ToggleGroup right; //I called it right in SceneBuilder.
later somewhere in method.
RadioButton selectedRadioButton = (RadioButton) right.getSelectedToggle(); String toogleGroupValue = selectedRadioButton.getText();
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 } } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With