bam*_*mmy 1 for-loop javafx arraylist radio-button
我想知道是否可以在按下某个 RadioButton 时找到索引,或者在 RadioButton 时传递 myBuns.get(i)。使用下面的代码创建 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);
}
Run Code Online (Sandbox Code Playgroud)
感谢您的任何帮助或建议!
You can get the index of the selected toggle using:
toggleGroup.getToggles().indexOf(toggleGroup.getSelectedToggle());
Run Code Online (Sandbox Code Playgroud)
And the text of the selected toggle using:
((RadioButton) toggleGroup.getSelectedToggle()).getText();
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)