JavaFX单选按钮
JavaFX RadioButton是可以选择或者不选择的按钮。 " RadioButton"与JavaFX ToggleButton非常相似,但是不同之处在于,一旦选中" RadioButton",就不能"取消选择"。如果" RadioButton"是" ToggleGroup"的一部分,则一旦首次选择了" RadioButton",就必须在" ToggleGroup"中选择一个" RadioButton"。
JavaFX RadioButton由类javafx.scene.control.RadioButton表示。 RadioButton类是ToggleButton类的子类。
创建一个RadioButton
使用其构造函数创建一个JavaFXRadioButton。这是一个JavaFXRadioButton实例化示例:
RadioButton radioButton1 = new RadioButton("Left");
作为参数传递给" RadioButton"构造函数的字符串显示在" RadioButton"旁边。
将单选按钮添加到场景图
要使" RadioButton"可见,必须将其添加到JavaFX应用程序的场景图中。这意味着将" RadioButton"添加到"场景",或者作为添加到"场景"对象的布局的子代。
这是一个将JavaFXRadioButton添加到场景图的示例:
package com.Hyman.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class RadioButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
RadioButton radioButton1 = new RadioButton("Left");
HBox hbox = new HBox(radioButton1);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
通过运行此示例生成的应用程序如下所示:
读取所选状态
" RadioButton"类具有名为" isSelected"的方法,该方法可让我们确定是否选择了" RadioButton"。如果选择了" RadioButton",那么" isSelected()"方法将返回一个"布尔",其值为" true",否则为" false"。这是一个例子:
boolean isSelected = radioButton1.isSelected();
切换组
我们可以将JavaFXRadioButton实例分组为ToggleGroup。一个"切换组"最多可以随时选择一个"单选按钮"。
这是一个JavaFXToggleGroup示例:
package com.Hyman.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class RadioButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
RadioButton radioButton1 = new RadioButton("Left");
RadioButton radioButton2 = new RadioButton("Right");
RadioButton radioButton3 = new RadioButton("Up");
RadioButton radioButton4 = new RadioButton("Down");
ToggleGroup radioGroup = new ToggleGroup();
radioButton1.setToggleGroup(radioGroup);
radioButton2.setToggleGroup(radioGroup);
radioButton3.setToggleGroup(radioGroup);
radioButton4.setToggleGroup(radioGroup);
HBox hbox = new HBox(radioButton1, radioButton2, radioButton3, radioButton4);
Scene scene = new Scene(hbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
通过运行此示例生成的应用程序如下所示:
读取切换组的选定状态
我们可以使用" getSelectedToggle()"方法读取选择了" ToggleGroup"中的哪个" RadioButton",如下所示:
RadioButton selectedRadioButton =
(RadioButton) toggleGroup.getSelectedToggle();
如果未选择任何" RadioButton",则" getSelectedToggle()"方法将返回" null"。

