JavaFX: Setting up radio button group

This entry is part 31 of 55 in the series JavaFX

As you are well aware, radio buttons work in group.

Once we have declared the radio buttons, we then need to create a group for the buttons with the ToggleGroup class and add the radio buttons to the toggle group.

package javafxapplication24;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;

public class JavaFXApplication24 extends Application {

    RadioButton rb1 = new RadioButton("Rock");
    RadioButton rb2 = new RadioButton("Country");

    ToggleGroup rbGroup = new ToggleGroup();

    @Override
    public void start(Stage stage) {

        stage.setTitle("JavaFX Program!");

        VBox vbox_pane = new VBox();
        vbox_pane.setAlignment(Pos.CENTER);

        HBox hbox1 = new HBox();
        HBox hbox2 = new HBox();
        HBox hbox3 = new HBox();

        hbox1.setPadding(new Insets(15, 12, 15, 12));
        hbox1.setAlignment(Pos.CENTER_LEFT);

        hbox2.setPadding(new Insets(15, 12, 15, 12));

        rb1.setToggleGroup(rbGroup);
        rb2.setToggleGroup(rbGroup);

        hbox2.setAlignment(Pos.CENTER_LEFT);

        Button btn = new Button("Submit");

        btn.setOnAction(e -> buttonClick());

        hbox1.getChildren().add(rb1);
        hbox2.getChildren().add(rb2);
        hbox3.getChildren().add(btn);

        vbox_pane.getChildren().addAll(hbox1, hbox2, btn);

        Scene scene = new Scene(vbox_pane, 300, 250);
        stage.setScene(scene);

        stage.show();
    }

    private void buttonClick() {

        if (rb1.isSelected()) {
            System.out.println("You like Rock music");
        }
        if (rb2.isSelected()) {
            System.out.println("You like Country music");
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

radio1

radio2

 

Series Navigation<< JavaFX: Which checkbox is checked
JavaFX: Setting up a choice box >>

Leave a comment

Leave a Reply