这是我的程序的 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();
}
}
我的问题是单选按钮无法正常工作。当您单击某个按钮时,它会保持选中状态,除非您再次单击它,并且按下另一个按钮时它不会取消选择。我看过许多其他线程,但大多数都只是关于如何将 RadioButtons 添加到 ToggleGroup 等。我有 Toggle 组,并添加了它们,那么有什么问题吗? (我正在学习 JavaFX,我通常在 swing 中做 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);
关于JavaFX RadioButton 无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512435/