To Handle selection change event on RadioButton within group of radio buttons in JavaFX
P:Full source
import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; 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.FlowPane; import javafx.stage.Stage; public class Main extends Application { private Label response; public static void main(String[] args) { launch(args);//w w w . j av a 2s . co 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, 220, 120); myStage.setScene(myScene); response = new Label(""); // Create the radio buttons. RadioButton rbOne = new RadioButton("One"); RadioButton rbTwo = new RadioButton("Two"); RadioButton rbThree = new RadioButton("Three"); // Create a toggle group. ToggleGroup tg = new ToggleGroup(); // Add each button to a toggle group. rbOne.setToggleGroup(tg); rbTwo.setToggleGroup(tg); rbThree.setToggleGroup(tg); // Handle action events for the radio buttons. rbOne.setOnAction(e -> { response.setText("Transport selected is train."); }); rbTwo.setOnAction(e -> { response.setText("Transport selected is car."); }); rbThree.setOnAction(e -> { response.setText("Transport selected is airplane."); }); // Fire the event for the first selection. rbOne.fire(); // Use a change listener to respond to a change of selection within // the group of radio buttons. tg.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { public void changed(ObservableValue<? extends Toggle> changed, Toggle oldVal, Toggle newVal) { // Cast new to RadioButton. RadioButton rb = (RadioButton) newVal; // Display the selection. response.setText("Transport selected is " + rb.getText()); } }); // Add the label and buttons to the scene graph. rootNode.getChildren().addAll(rbOne, rbTwo, rbThree, response); myStage.show(); } }