Q:

How to find index or information of clicked RadioButton

I was wondering if there was anyway to either find the index when a certain RadioButton is pressed or to pass myBuns.get(i) when the RadioButton.  Using the code below to create the RadioButtons
RadioButton rButton;
for (i = 0; i < myBuns.size(); i ++){
        rButton = new RadioButton("" + myBuns.get(i));
        rButton.setToggleGroup(bunGroup);
        rButton.setOnAction(this);
        this.getChildren().add(rButton);
    }

Thanks for any help or suggestions!

A:

You can get the index of the selected toggle using:
toggleGroup.getToggles().indexOf(toggleGroup.getSelectedToggle());

And the text of the selected toggle using:
 ((RadioButton) toggleGroup.getSelectedToggle()).getText();

By placing the code in the change listener for the selected toggle property, you can monitor when the selected toggle changes and take action as appropriate.
Sample App

import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.util.stream.*;

public class ToggleIndexer extends Application {    
    @Override
    public void start(final Stage stage) throws Exception {
        ToggleGroup toggleGroup = new ToggleGroup();
        ObservableList<RadioButton> buttons = IntStream.range(0, 5)
                .mapToObj(i -> new RadioButton("Radio " + i))
                .collect(Collectors.toCollection(FXCollections::observableArrayList));
        toggleGroup.getToggles().setAll(buttons);

        Label selectedIndex = new Label();
        selectedIndex.setFont(Font.font("monospace"));
        Label selectedItem = new Label();
        selectedItem.setFont(Font.font("monospace"));

        toggleGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == null) {
                selectedIndex.setText("");
                selectedItem.setText("");
            } else {
                final int selectedIndexValue =
                        toggleGroup.getToggles().indexOf(newValue);
                selectedIndex.setText("Selected Index: " + selectedIndexValue);

                final String selectedItemText =
                        ((RadioButton) toggleGroup.getSelectedToggle()).getText();
                selectedItem.setText( "Selected Item:  " + selectedItemText);
            }
        });

        VBox layout = new VBox(8);
        layout.setPadding(new Insets(10));
        layout.setPrefWidth(250);
        layout.getChildren().setAll(buttons);
        layout.getChildren().addAll(selectedItem, selectedIndex);

        stage.setScene(new Scene(layout));
        stage.show();
    }

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

