为什么我的ToggleGroup变量总是为空?

时间:2018-03-06 09:32:25

标签: javafx

我定义了以下 FirstWindow.fxml 文件:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="switcherContainer" layoutX="0.0" layoutY="0.0" prefHeight="170.0" prefWidth="200.0"
                xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" 
                fx:controller="rep.ButtonController">

                <fx:define>
                     <ToggleGroup fx:id="rType"/>  
                </fx:define>

                <Label layoutX="35.0" layoutY="25.0" prefHeight="17.0" prefWidth="260.0" text="Choose the report type:" />

                <RadioButton layoutX="35.0" layoutY="60.0"  mnemonicParsing="false" text="A" toggleGroup="$rType" />
                <RadioButton layoutX="35.0" layoutY="80.0"  mnemonicParsing="false" text="B" toggleGroup="$rType" />
                <RadioButton layoutX="35.0" layoutY="100.0" mnemonicParsing="false" text="C" toggleGroup="$rType" />
                <RadioButton layoutX="35.0" layoutY="120.0" mnemonicParsing="false" text="D" toggleGroup="$rType" />  
</AnchorPane>

我在 Main 类中添加了 FirstWindow.fxml 文件:

AnchorPane rootPane = (AnchorPane) FXMLLoader.load(getClass().getResource("/rep/RootScene.fxml"));
primaryStage.setTitle("Report Generation");
primaryStage.setScene(new Scene(rootPane));     
AnchorPane innerPane = (AnchorPane) FXMLLoader.load(getClass().getResource("/rep/FirstWindow.fxml"));
rootPane.getChildren().addAll(innerPane);       
primaryStage.show();

我的 ButtonController 类看起来像这样:

public class ButtonController implements Initializable {
    static int step = 0;

    @FXML
    private Button nextButton;

    @FXML
    ToggleGroup rType;

    @Override
    public void initialize(URL location, ResourceBundle resources) {          
    }

    public void onNextButtonClick(ActionEvent event) {
         System.out.println("Button Clicked!");      
         try {              
             if (rType != null) {
                 System.out.println("RadioButton selected: " + rType.getSelectedToggle().getUserData().toString());
             } else {
                 System.out.println("rType is null");
             }       

             ...
             primaryStage.show();       
         } catch (Exception ex) {
             System.out.println("Exception: " + ex);        
         }
    }
}

但我总是在控制台中获得以下输出:

  

rType为空

为什么呢?以及如何解决它?

0 个答案:

没有答案