如何在JavaFX中默认检查单选按钮?

时间:2019-06-15 21:58:55

标签: java javafx radio-button javafx-8

我正在建造一块石头,剪刀,纸张应用程序作为大学作业。我应该使用单选按钮,并且由于它是一个游戏,因此应该一次允许一个选定的按钮。

我尝试创建ToggleGroups并将默认情况下的按钮之一设置为选中状态,但是它不起作用!当我运行该应用程序时,它仍然允许我选择多个按钮:( 我想念什么?

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("../view/QuilometrosPorLitroView.fxml"));
        primaryStage.setTitle("Pedra, Papel, Tesoura");
        primaryStage.setScene(new Scene(root, 428, 336));
        primaryStage.setResizable(false);
        primaryStage.show();
        Controller.selectButtonDefault();
    }


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

public class Controller {

    @FXML
    public static
    RadioButton tesoura = new RadioButton();
    @FXML
    public static
    RadioButton pedra = new RadioButton();
    @FXML
    public static
    RadioButton papel = new RadioButton();

    public static void selectButtonDefault() {
        ToggleGroup group = new ToggleGroup();

        tesoura.setToggleGroup(group);
        tesoura.setSelected(true);
        pedra.setToggleGroup(group);
        papel.setToggleGroup(group);

    }

1 个答案:

答案 0 :(得分:0)

@FXML public static RadioButton tesoura = new RadioButton(); 
@FXML public static RadioButton pedra = new RadioButton(); 
@FXML public static RadioButton papel = new RadioButton();

应更改为

@FXML private RadioButton tesoura;
@FXML private RadioButton pedra; 
@FXML private RadioButton papel;