1

Until now I've been always setting up the controller from the fxml file like this in the root element:

fx:controller = "control.MainController" 

I have a window with 2 tabs, each of them full of buttons, tables and other elements... To keep my project in order and easy to read/maintain I would like to separate the controller code in FirstTabController and SecondTabController. How to do it?

Can I use two different files as controller classes of the same fxml file?

Robb1
  • 4,587
  • 6
  • 31
  • 60

1 Answers1

3

Look at the JavaFX TabPane - One controller for each tab - you should use fx:include tag.

Main.java (assuming all the files are in the sample package)

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;

public class Main extends Application {

  public void start(Stage stage) {
    Parent root = null;

    try {
      root = FXMLLoader.load(getClass().getResource("sample.fxml"));
    } catch (IOException e) {
      e.printStackTrace();
    }

    Scene scene = new Scene(root, 300, 275);
    stage.setTitle("FXML Welcome");
    stage.setScene(scene);
    stage.show();
  }

  public static void main(String[] args) {
    launch();
  }
}

sample.fxml

<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.Tab?>

<TabPane xmlns:fx="http://javafx.com/fxml">
    <Tab text="Tab 1">
        <content>
            <fx:include source="tab1.fxml"/>
        </content>
    </Tab>
    <Tab text="Tab 2">
        <content>
            <fx:include source="tab2.fxml"/>
        </content>
    </Tab>
</TabPane>

tab1.fxml

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Label?>
<StackPane xmlns:fx="http://javafx.com/fxml" fx:controller="sample.TabOneController">
    <Label text="Tab 1"/>
</StackPane>

tab2.fxml

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Label?>
<StackPane xmlns:fx="http://javafx.com/fxml" fx:controller="sample.TabTwoController">
    <Label text="Tab 2"/>
</StackPane>

FXML files added with the fx:include tag are separate files which can have separate controllers.