title: JavaFX : How to dynamically change the controller in the same fxml file?
body: <p>Experts! I just want to use a button for the couple of controllers so that I want to make my code be short. In bottom of a boderpane, I made buttons for changing the view of center of the borderpane, and once the next button clicked, it's changed another view that located in the center of the borderpane. However, if I click the check button, I expected that the massage for displayMassageLabel would come up, but it makes an error.. Is there anyone to  solve this problem..?
  Here are sample codes I simply made below.</p>
  
  <p>ChangeControllerTestMain.java</p>
  
  <pre><code>package javafxapplication2;
  
  import javafx.application.Application;
  import javafx.fxml.FXMLLoader;
  import javafx.scene.Parent;
  import javafx.scene.Scene;
  import javafx.stage.Stage;
  
  /**
   *
   * @author James
   */
  public class ChangeControllerTestMain extends Application {
  
      @Override
      public void start(Stage stage) throws Exception {
          Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
  
          Scene scene = new Scene(root);
  
          stage.setScene(scene);
          stage.show();
      }
  
      /**
       * @param args the command line arguments
       */
      public static void main(String[] args) {
          launch(args);
      }
  
  }
  </code></pre>
  
  <p>Main.fxml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  
  &lt;?import java.lang.*?&gt;
  &lt;?import java.util.*?&gt;
  &lt;?import javafx.scene.*?&gt;
  &lt;?import javafx.scene.control.*?&gt;
  &lt;?import javafx.scene.layout.*?&gt;
  
  &lt;BorderPane fx:id="borderPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication2.MainController"&gt;
     &lt;bottom&gt;
        &lt;HBox alignment="CENTER" prefHeight="39.0" prefWidth="600.0" spacing="100.0" BorderPane.alignment="CENTER"&gt;
           &lt;children&gt;
              &lt;Button fx:id="backButton" mnemonicParsing="false" onAction="#handleBackButtonAction" text="&amp;lt;Back" /&gt;
              &lt;Button fx:id="checkButton" mnemonicParsing="false" onAction="#handleCheckButtonAction" text="Check" /&gt;
              &lt;Button fx:id="nextButton" mnemonicParsing="false" onAction="#handleNextButtonAction" text="Next&amp;gt;" /&gt;
           &lt;/children&gt;&lt;/HBox&gt;
     &lt;/bottom&gt;
  &lt;/BorderPane&gt;
  </code></pre>
  
  <p>MainColtroller.java</p>
  
  <pre><code>package javafxapplication2;
  
  import java.net.URL;
  import java.util.ResourceBundle;
  import javafx.event.ActionEvent;
  import javafx.fxml.FXML;
  import javafx.fxml.FXMLLoader;
  import javafx.fxml.Initializable;
  import javafx.scene.control.Button;
  import javafx.scene.control.Label;
  import javafx.scene.layout.AnchorPane;
  import javafx.scene.layout.BorderPane;
  
  /**
   *
   * @author James
   */
  public class MainController implements Initializable {
  
      @FXML
      private BorderPane borderPane;
      private AnchorPane anchorPane;
      private Label displayMassageLabel;
  
      @FXML
      private Button backButton;
      @FXML
      private Button checkButton;
      @FXML
      private Button nextButton;
  
      private int currentMenuNum;
      private String currentViewerPath;
      private String pathList[] = {"StartDisplay.fxml", "Menu1Display.fxml", "Menu2Display.fxml", "Menu3Display.fxml"};
  
      private Menu1DisplayController menu1DisplayController = new Menu1DisplayController();
      private Menu2DisplayController menu2DisplayController = new Menu2DisplayController();
      private Menu3DisplayController menu3DisplayController = new Menu3DisplayController();
  
      @Override
      public void initialize(URL url, ResourceBundle rb) {
          // TODO
          currentMenuNum = 0;
          currentViewerPath = pathList[currentMenuNum];
          System.out.println(currentViewerPath);
          setControlItems(currentViewerPath, currentMenuNum);
      }
  
      private void setControlItems(String path, int currentMenuNum) {
          //Display setting for menu
          FXMLLoader fxmlLoader = new FXMLLoader();
          try {
              fxmlLoader.setLocation(getClass().getResource(path));
              anchorPane = fxmlLoader.load();
              //connectionViewerController = (ConnectionViewerController) fxmlLoader.getController();
          } catch (Exception e) {
              System.out.println(e.getStackTrace().toString());
              System.out.println(e.getMessage());
          }
          borderPane.setCenter(anchorPane);
  
          if (currentMenuNum == 1) {
              menu1DisplayController = (Menu1DisplayController) fxmlLoader.getController();
          } else if (currentMenuNum == 2) {
              menu2DisplayController = (Menu2DisplayController) fxmlLoader.getController();
          } else if (currentMenuNum == 3) {
              menu3DisplayController = (Menu3DisplayController) fxmlLoader.getController();
          }
      }
  
      private String getCurrentViewerPath(int currentMenuNum) {
          currentViewerPath = pathList[currentMenuNum];
          return currentViewerPath;
      }
  
      @FXML
      private void handleBackButtonAction(ActionEvent event) {
          if (currentMenuNum == 0) {
              return;
          }
          currentMenuNum = currentMenuNum - 1;
          currentViewerPath = getCurrentViewerPath(currentMenuNum);
          setControlItems(currentViewerPath, currentMenuNum);
      }
  
      @FXML
      private void handleNextButtonAction(ActionEvent event) {
          currentMenuNum = currentMenuNum + 1;
          currentViewerPath = getCurrentViewerPath(currentMenuNum);
          setControlItems(currentViewerPath, currentMenuNum);
      }
  
      @FXML
      private void handleCheckButtonAction(ActionEvent event) {
          displayMassageLabel.setText("Welcome Menu " + currentMenuNum);
      }
  }
  </code></pre>
  
  <p>StartDisplay.fxml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  
  &lt;?import java.lang.*?&gt;
  &lt;?import java.util.*?&gt;
  &lt;?import javafx.scene.*?&gt;
  &lt;?import javafx.scene.control.*?&gt;
  &lt;?import javafx.scene.layout.*?&gt;
  
  &lt;AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"&gt;
     &lt;children&gt;
        &lt;VBox alignment="CENTER" layoutX="10.0" layoutY="10.0" prefHeight="361.0" prefWidth="600.0" spacing="20.0"&gt;
           &lt;children&gt;
              &lt;Label text="Display Message" /&gt;
              &lt;Label text="Start Display" /&gt;
              &lt;Label fx:id="displayMassageLabel" /&gt;
           &lt;/children&gt;
        &lt;/VBox&gt;
     &lt;/children&gt;
  &lt;/AnchorPane&gt;
  </code></pre>
  
  <p>Menu1DisplayController.java</p>
  
  <pre><code>package javafxapplication2;
  
  import java.net.URL;
  import java.util.ResourceBundle;
  import javafx.event.ActionEvent;
  import javafx.fxml.FXML;
  import javafx.fxml.Initializable;
  import javafx.scene.control.Label;
  
  /**
   * FXML Controller class
   *
   * @author James
   */
  public class Menu1DisplayController implements Initializable {
      @FXML
      private Label displayMassageLabel;
  
      /**
       * Initializes the controller class.
       */
      @Override
      public void initialize(URL url, ResourceBundle rb) {
          // TODO
      }   
  
      @FXML
      private void handleCheckButtonAction(ActionEvent event) {
          displayMassageLabel.setText("Welcome Menu 1");
      }
  
  }
  </code></pre>
  
  <p>Menu1Display.fxml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  
  &lt;?import java.lang.*?&gt;
  &lt;?import java.util.*?&gt;
  &lt;?import javafx.scene.*?&gt;
  &lt;?import javafx.scene.control.*?&gt;
  &lt;?import javafx.scene.layout.*?&gt;
  
  &lt;AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication2.Menu1DisplayController"&gt;
     &lt;children&gt;
        &lt;VBox alignment="CENTER" layoutX="10.0" layoutY="10.0" prefHeight="361.0" prefWidth="600.0" spacing="20.0"&gt;
           &lt;children&gt;
              &lt;Label text="Display Message" /&gt;
              &lt;Label text="Current Menu is 1" /&gt;
              &lt;Label fx:id="displayMassageLabel" /&gt;
           &lt;/children&gt;
        &lt;/VBox&gt;
     &lt;/children&gt;
  &lt;/AnchorPane&gt;
  </code></pre>
  
  <p>FXML files and controllers  for menu2 and 3 are the same as menu 1's.
  pleas help me.</p>
  
  <p>These are errors..</p>
  
  <pre><code>Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
      at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1770)
      at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1653)
      at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
      at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
      at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
      at javafx.event.Event.fireEvent(Event.java:198)
      at javafx.scene.Node.fireEvent(Node.java:8390)
      at javafx.scene.control.Button.fire(Button.java:185)
      at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
      at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
      at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
      at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
      at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
      at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
      at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
      at javafx.event.Event.fireEvent(Event.java:198)
      at javafx.scene.Scene$MouseHandler.process(Scene.java:3758)
      at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3486)
      at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
      at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2495)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:350)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
      at java.security.AccessController.doPrivileged(Native Method)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(GlassViewEventHandler.java:385)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$105/472212858.get(Unknown Source)
      at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:404)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:384)
      at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
      at com.sun.glass.ui.View.notifyMouse(View.java:927)
      at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
      at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
      at com.sun.glass.ui.win.WinApplication$$Lambda$36/1963387170.run(Unknown Source)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: java.lang.reflect.InvocationTargetException
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:497)
      at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
      at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:497)
      at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
      at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1765)
      ... 50 more
  Caused by: java.lang.NullPointerException
      at javafxapplication2.MainController.handleCheckButtonAction(MainController.java:101)
      ... 60 more
  </code></pre>