JavaFX RadioButton是可以选择或不选择的按钮。RadioButton与JavaFX ToggleButton非常相似,但区别在于RadioButton一旦被选中,就不能“取消选中”。如果RadioButton是ToggleGroup的一部分,则在首次选择RadioButton后,必须在ToggleGroup中选择一个RadioButton。下面介绍 RadioButton如何使用:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class RadioButtonDemo extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Label optionName = new Label();//显示选择哪个选项
RadioButton button1 = new RadioButton("小学");
RadioButton button2 = new RadioButton("初中");
RadioButton button3 = new RadioButton("高中");
RadioButton button4 = new RadioButton("本科");
RadioButton button5 = new RadioButton("硕士");
RadioButton button6 = new RadioButton("博士");
/**
* 将6个RadioButton绑定到同一个组,这样可以实现同组只能选择一个选项。
*/
ToggleGroup group = new ToggleGroup();
button1.setToggleGroup(group);
button2.setToggleGroup(group);
button3.setToggleGroup(group);
button4.setToggleGroup(group);
button5.setToggleGroup(group);
button6.setToggleGroup(group);
/**
* 监听选择的选项
*/
group.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
String selectOption = ((RadioButton)newValue).getText();
System.out.println("选择了:"+selectOption);
optionName.setText(selectOption);
});
/**
* 监听按钮选中状态变化
*/
button1.selectedProperty().addListener((observable, oldValue, newValue)
-> System.out.println(button1.getText()+"是否被选中了:"+newValue));
/**
* 按钮点击事件
*/
button1.setOnAction(event -> System.out.println("点击了"+button1.getText()));
VBox root=new VBox();
root.setSpacing(20);
root.setPadding(new Insets(10,10,10,10));
root.getChildren().addAll(button1,button2,button3,button4,button5,button6,optionName);
Scene scene=new Scene(root,400,300);
primaryStage.setScene(scene);
primaryStage.setTitle("Radio Button 示例");
primaryStage.show();
}
}
运行效果: