如何使用 JavaFX 创建单选按钮?
javafxobject oriented programmingprogramming更新于 2026/1/4 8:12:17
按钮是一种组件,按下时会执行操作(如提交、登录等)。它通常标有文本或图像,指定相应的操作。
单选按钮是一种圆形按钮。它有两种状态,选中和取消选中。通常,单选按钮使用切换组进行分组,您只能选择其中一个。
您可以通过实例化 javafx.scene.control.RadioButton 类(它是 ToggleButton 类的子类)在 JavaFX 中创建单选按钮。每当按下或释放单选按钮时都会生成操作。您可以使用 setToggleGroup() 方法将单选按钮设置为组。
示例
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class RadioButtonExample extends Application {
@Override
public void start(Stage stage) {
//创建切换按钮
RadioButton button1 = new RadioButton("Java");
RadioButton button2 = new RadioButton("Python");
RadioButton button3 = new RadioButton("C++");
//切换按钮组
ToggleGroup group = new ToggleGroup();
button1.setToggleGroup(group);
button2.setToggleGroup(group);
button3.setToggleGroup(group);
//将切换按钮添加到窗格
VBox box = new VBox(5);
box.setFillWidth(false);
box.setPadding(new Insets(5, 5, 5, 50));
box.getChildren().addAll(button1, button2, button3);
//设置舞台
Scene scene = new Scene(box, 595, 150, Color.BEIGE);
stage.setTitle("Toggled Button Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
输出


