JavaFX Radio Button Example

In this JavaFX example, we will see how to use the JavaFX RadioButton control with an example.

RadioButton is usually used to create a mutually exclusive series of items. Only one RadioButton can be selected when placed in a ToggleGroup. When a RadioButton is selected an ActionEvent is sent.

The JavaFX RadioButton is represented by the class javafx.scene.control.RadioButton

JavaFX RadioButton Example

The example has three radio buttons. By placing them in a toggle group, only one of them can be selected at a time.
package sample;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
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.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    private final double BORDER = 10d;
    private Label lbl2;

    public void start(Stage stage) {


    private void initUI(Stage stage) {

        var root = new AnchorPane();

        var vbox = new VBox(10);
        vbox.setPadding(new Insets(10));

        var lbl1 = new Label("Difficulty");

        lbl2 = new Label("");
        lbl2.setStyle("-fx-background-color:wheat; -fx-padding: 0 0 0 5");
        lbl2.prefWidthProperty().bind(stage.widthProperty().subtract(2 * BORDER));

        var tg = new ToggleGroup();
        tg.selectedToggleProperty().addListener(new MyToggleListener());

        var rb1 = new RadioButton("Easy");

        var rb2 = new RadioButton("Medium");

        var rb3 = new RadioButton("Hard");

        vbox.getChildren().addAll(lbl1, rb1, rb2, rb3);
        root.getChildren().addAll(vbox, lbl2);

        AnchorPane.setTopAnchor(vbox, BORDER);
        AnchorPane.setBottomAnchor(lbl2, BORDER);
        AnchorPane.setLeftAnchor(lbl2, BORDER);

        var scene = new Scene(root, 300, 250);


    private class MyToggleListener implements ChangeListener<Toggle> {

        public void changed(ObservableValue<? extends Toggle> observable,
                            Toggle oldValue, Toggle newValue) {

            var rb = (RadioButton) newValue;
            String txt = rb.getText();

    public static void main(String[] args) {


Related JavaFX Examples