1

我在相应的控制器中有一个使用 FXML 创建的窗口,我有一个按钮,当单击特定按钮时它会加载一个小框。该盒子也是使用 FXML 设计的。

当我加载该框并将其添加到窗口中时,出现此错误:

javafx.fxml.LoadException: Root value already specified.
    at javafx.fxml.FXMLLoader.createElement(FXMLLoader.java:2362)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2311)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2131)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2028)
    at com.clientgui.DataPage.openStaticData(DataPage.java:79)
...

这是我的代码:

private void openStaticData(int dataObjectId, String titel)
{
    try
    {
        URL location = getClass().getResource("StaticDataBox.fxml");
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(location);
        loader.setBuilderFactory(new JavaFXBuilderFactory());
        loader.load();
        final Region page = (Region) loader.load();  //line 79

        StaticDataBox staticDataBox = (StaticDataBox) loader.getController();
        staticDataBox.setDataObjectId(dataObjectId);
        staticDataBox.setTitel(titel);

        Platform.runLater(new Runnable()
        {
            @Override
            public void run()
            {
                getChildren().add(page);
            }
        });

    } catch (IOException ex)
    {
        Logger.getLogger(DataPage.class.getName()).log(Level.SEVERE, null, ex);
    }
}

主窗口 FXML:

<fx:root type="javafx.scene.layout.StackPane" xmlns:fx="http://javafx.com/fxml" fx:controller="com.clientgui.ClientGUI" prefHeight="675" prefWidth="1200.0" fx:id="root" styleClass="root">
...
</fx:root>

我要动态创建的框的 FXML:

<VBox id="VBox" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="com.clientgui.StaticDataBox" styleClass="data-box">
...
</VBox>
4

1 回答 1

3

You are using the instantiated version of FXMLLoader, i.e. non-static load() method of it. This method obligates that the location is set prior calling it, as explained in its javadoc. So by calling loader.load() method, FXMLLoader parses the fxml file at a given location, initializes the controller and constructs the node graph. If the loader.load() method invoked again, FXMLLoader detects that the root has been already set and throws the "Root value already specified." exception.
However invoking the static load() methods of FXMLLoader over and over, will not cause this exception. Because the fxml file parsing and other stuff are performed from the scratch over again independently from each call, on each call.

于 2013-11-07T20:06:35.890 回答