如何从ToggleGroup获取选定的单选按钮 [英] How to get selected radio button from ToggleGroup
问题描述
我正在研究JavaFX 8和 SceneBuilder
。我在FXML文件中创建了一些单选按钮,并将 toggleGroup
名称指定为单选按钮列表。所以,现在我想在我的控制器中获得 toggleGroup
的所选单选按钮,是否需要将所有单选按钮再次作为控制器中的字段,或者只是 toggleGroup
对象将获取所选的单选按钮(仅限该单选按钮的文本,而不是按钮对象)。
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).
推荐答案
假设您有一个切换组和属于该组的三个单选按钮。
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
}
}
});
这篇关于如何从ToggleGroup获取选定的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!