JavaFX RadioButton 不能正常工作?

JavaFX RadioButton's not working correctly?

所以这是我程序的 UI 部分:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TestClass extends Application {

Scene scene;
String fileName;
Button button;
Label fileLabel, dotText;
TextField fileNameText;
RadioButton totalRadio, aRadio, bRadio, cRadio;
ToggleGroup sumGroup;


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

@Override
public void start(Stage primaryStage) {
    GridPane layout = new GridPane();
    layout.setVgap(5);
    layout.setHgap(5);

    //Adds button
    button = new Button("Sum file");
    button.setOnAction(e -> {
        fileName = "C:\Users\Luke\Desktop\" + fileNameText.getText() + ".txt";
    });
    layout.setConstraints(button, 1, 1);

    //Adds label
    fileLabel = new Label("File name: ");
    layout.setConstraints(fileLabel, 0, 0);

    //Adds TextField
    fileNameText = new TextField();
    fileNameText.setPrefWidth(100);
    layout.setConstraints(fileNameText, 1, 0);

    //Adds Label
    dotText = new Label(".txt");
    layout.setConstraints(dotText, 2, 0);

    //Makes Button group
    sumGroup = new ToggleGroup();

    //Adding all radio buttons
    totalRadio = new RadioButton("Total");
    totalRadio.setToggleGroup(sumGroup);
    totalRadio.setSelected(true);
    layout.setConstraints(totalRadio, 1, 2);

    aRadio = new RadioButton("A Branch");
    totalRadio.setToggleGroup(sumGroup);
    layout.setConstraints(aRadio, 1, 3);

    bRadio = new RadioButton("B Branch");
    totalRadio.setToggleGroup(sumGroup);
    layout.setConstraints(bRadio, 1, 4);

    cRadio = new RadioButton("C Branch");
    totalRadio.setToggleGroup(sumGroup);
    layout.setConstraints(cRadio, 1, 5);

    //Adds components to scene
    layout.getChildren().addAll(fileLabel, fileNameText, button, dotText, totalRadio, aRadio, bRadio, cRadio);
    scene = new Scene(layout, 230, 185);

    primaryStage.setScene(scene);
    primaryStage.show();
    }
}

我的问题是单选按钮没有正常工作。当您单击一个按钮时,它会保持 selected,除非您再次单击它,并且当另一个按钮被按下时它不会取消 select。我看过许多其他线程,但其中大部分只是关于如何将 RadioButtons 添加到 ToggleGroup 等。我有 Toggle 组,并添加了它们,所以有什么问题吗? (我正在学习 JavaFX,我通常在摇摆中做 GUI。)

您多次设置 totalRadio.setToggleGroup 但没有在 aRadio,bRadio,cRadio 上设置。

更改为:

aRadio = new RadioButton("A Branch");
aRadio.setToggleGroup(sumGroup);
layout.setConstraints(aRadio, 1, 3);

bRadio = new RadioButton("B Branch");
bRadio.setToggleGroup(sumGroup);
layout.setConstraints(bRadio, 1, 4);

cRadio = new RadioButton("C Branch");
cRadio.setToggleGroup(sumGroup);
layout.setConstraints(cRadio, 1, 5);