获取并记住JavaFX中选定的单选按钮
我在JavaFx应用程序中使用了这个方法来创建获取并记住JavaFX中选定的单选按钮,java,javafx,Java,Javafx,我在JavaFx应用程序中使用了这个方法来创建RadioButtons private HBox createModesRadios(IntegerProperty count, Mode... modes) { ToggleGroup group = new ToggleGroup(); HBox result = new HBox(50); result.setPadding(new Insets(20, 0, 0, 0)); result.setAlignm
RadioButton
s
private HBox createModesRadios(IntegerProperty count, Mode... modes) {
ToggleGroup group = new ToggleGroup();
HBox result = new HBox(50);
result.setPadding(new Insets(20, 0, 0, 0));
result.setAlignment(Pos.CENTER);
for (Mode mode : modes) {
RadioButton radio = new RadioButton(mode.getText());
radio.setToggleGroup(group);
radio.setUserData(mode);
result.getChildren().add(radio);
}
if (modes.length > 0) {
group.selectToggle((Toggle) result.getChildren().get(0));
count.bind(Bindings.createIntegerBinding(() -> ((Mode) group.getSelectedToggle().getUserData()).getCount(), group.selectedToggleProperty()));
} else {
count.set(0);
}
return result;
}
它在我的控制器类中的我的initialize()
方法中被以下方式调用HBox radioBox=createModesRadios(elementCount,modes)代码>
这是助手类模式:
public class Mode {
private final String text;
private final int count;
public Mode(String text, int count) {
this.text = text;
this.count = count;
}
public String getText() {
return text;
}
public int getCount() {
return count;
}
}
如何保存用户选择的按钮?最好将所选按钮的mode.getText()
方法存储在变量String
中。此外,我还想将以前选择的按钮设置回原来的位置,以便应用程序能够记住该选项。您可以在控制器类的变量声明中添加类似的内容:私有列表radioButtonsList=new ArrayList()代码>
然后,您可以在您提到的方法中的for
循环中添加类似的内容
...
radioButtonsList.add(radio);
...
之后,您可以使用radioButtonList.get()调用所需的按钮