Modular tabs in JavaFX

In JavaFX, the UI and the application logic can be easily separated. The interface layout and design is written in FXML, and the logic goes in a Java class. FXML is an XML based markup language used for defining graphical user interfaces in JavaFX.

For more info about FXML, read Oracle's documentation.

In the root tag of an FXML file, specify the fully-qualified (include the package name) Java class to use as a controller with the fx:controller attribute.

        <AnchorPane
          fx:controller="controllers.MainController"
          xmlns:fx="http://javafx.com/fxml/1">...
      

The problem

If we have one FXML file and one Java controller, both of these files will be very large, hard to understand, and hard to debug. Using a single controller makes development more difficult and is not maintainable.

The solution

Modularize! Use the fx:include tag to include a FXML file inside another FXML file. Here is how the main window references the introduction tab that users see when they first open the application:

mainwindow.fxml

        <TabPane fx:id="tabPane">
          <Tab fx:id="introTab" text="Welcome">
            <fx:include source="intro_page.fxml"/>
          </Tab>...
      

introTab.fxml

        <GridPane fx:controller="controllers.InfoTab">
      

The root tag in introTab.fxml references the InfoTab.java file, which is the controller for the information tab.

Now we can separate the logic for each tab into independent files, making code easier to read by splitting a potentially large controller class into smaller, more manageable files.