title: JavaFX Root loading problems
body: <p>I am relatively new to JavaFX. I am trying to test design pattern where each fxml has its own controller with loader.</p>
  
  <p>Example:.</p>
  
  <p><strong>text.fxml</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;?import javafx.scene.layout.VBox?&gt;
  &lt;?import javafx.scene.control.Label?&gt;
  
  &lt;VBox&gt;
      &lt;children&gt;
          &lt;Label text="Hello world FXML"/&gt;
      &lt;/children&gt;
  &lt;/VBox&gt;
  </code></pre>
  
  <p><strong>MainController</strong></p>
  
  <pre><code>public class MainController extends VBox {
  
      public MainController() {
          FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/test.fxml"));
          loader.setController(this);
          try {
              loader.load();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p><strong>App</strong></p>
  
  <pre><code>public class App extends javafx.application.Application {
  
      @Override
      public void start(Stage primaryStage) {
          MainController mainController = new MainController();
          Stage stage = new Stage();
          stage.setScene(new Scene(mainController));
          stage.show();
      }
  
      public static void main(String[] args) {
          launch();
      }
  }
  </code></pre>
  
  <p>This does not work, I get an empty window when application is started:</p>
  
  <p><a href="https://i.stack.imgur.com/SjOiV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SjOiV.png" alt="enter image description here"></a></p>
  
  <p>If make some changes to controller and App:</p>
  
  <p><strong>controller</strong></p>
  
  <pre><code>private Parent root;
  
  public MainController() {
      FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/test.fxml"));
      loader.setController(this);
      try {
          root = loader.load();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  
  public Parent getRoot() {
      return root;
  }
  </code></pre>
  
  <p><strong>App</strong></p>
  
  <pre><code>stage.setScene(new Scene(mainController.getRoot()));
  </code></pre>
  
  <p>After this everything works as expected, Label with text can be seen in window.</p>
  
  <p>If I try to set root in controller:</p>
  
  <pre><code>loader.setRoot(this);
  </code></pre>
  
  <p>I get an error:</p>
  
  <pre><code>javafx.fxml.LoadException: Root value already specified.
  /C:/.../target/classes/fxml/test.fxml
  
      at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2621)
      ...
  </code></pre>
  
  <p><strong>Question:</strong> Can anyone with more experience in JavaFX advise me on this? What am I doing wrong? Is there a better way to achieve this?</p>