如何在JavaFX中使用单选按钮组?

5
我需要创建一个由两个单选按钮组成的组,并获取所选值的值。
1个回答

16

只需使用 ToggleGroup 即可。

RadioButton radioButton1 = ...
RadioButton radioButton2 = ...

// TODO: add RadioButtons to scene

ToggleGroup toggleGroup = new ToggleGroup();

radioButton1.setToggleGroup(toggleGroup);
radioButton2.setToggleGroup(toggleGroup);

// listen to changes in selected toggle
toggleGroup.selectedToggleProperty().addListener((observable, oldVal, newVal) -> System.out.println(newVal + " was selected"));

你也可以使用以下方式从ToggleGroup中检索所选的单选按钮:

toggleGroup.getSelectedToggle()

如果你想从提交按钮的处理程序或类似的地方执行此操作...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接