JavaFX RadioButton get selected

Introduction

To Get selected radio button in JavaFX

// Get the radio button that is currently selected. 
RadioButton rb = (RadioButton) tg.getSelectedToggle(); 
 
// Display the selection. 
response.setText(rb.getText() + " is confirmed."); 

Full source

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Separator;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage; 
 
public class Main extends Application { 
 
  private Label response; 
  private ToggleGroup tg; 
 
  public static void main(String[] args) { 
    launch(args);   //from w  w  w .  j  ava2 s .  c o m
  } 
 
  public void start(Stage myStage) { 
    myStage.setTitle("Demonstrate Radio Buttons"); 
 
    FlowPane rootNode = new FlowPane(10, 10); 
 
    rootNode.setAlignment(Pos.CENTER); 
 
    Scene myScene = new Scene(rootNode, 200, 140); 
 
    myStage.setScene(myScene); 
 
    // Create two labels. 
    Label choose = new Label("    Select a Transport Type    "); 
    response = new Label("No transport confirmed"); 
 
    Button btnConfirm = new Button("Confirm Transport Selection"); 
 
    // Create the radio buttons. 
    RadioButton rbOne = new RadioButton("One"); 
    RadioButton rbTwo = new RadioButton("Two"); 
    RadioButton rbThree = new RadioButton("Three"); 
 
    // Create a toggle group. 
    tg = new ToggleGroup(); 
 
    // Add each button to a toggle group. 
    rbOne.setToggleGroup(tg); 
    rbTwo.setToggleGroup(tg); 
    rbThree.setToggleGroup(tg); 
 
    // Initially select one of the radio buttons. 
    rbOne.setSelected(true); 
 
    // Handle action events for the confirm button. 
    btnConfirm.setOnAction(new EventHandler<ActionEvent>() { 
      public void handle(ActionEvent ae) { 
        // Get the radio button that is currently selected. 
        RadioButton rb = (RadioButton) tg.getSelectedToggle(); 
 
        // Display the selection. 
        response.setText(rb.getText() + " is confirmed."); 
      } 
    }); 
 
    Separator separator = new Separator(); 
    separator.setPrefWidth(180); 
 
    // Add the label and buttons to the scene graph. 
    rootNode.getChildren().addAll(choose, rbOne, rbTwo, rbThree, 
                                  separator, btnConfirm, response); 
 
    myStage.show(); 
  } 
}



PreviousNext

Related