One controller for each Tab - TabPane JavaFx

0

I have a TabPane with 5 tabs, each tab has a large number of controls, what I want is to assign each Tab / Tab its own controller, the scene builder only allows me to add a controller to the top panel (the root panel) , the idea of this is to fully respect the MVC pattern in addition to keeping the code maintainable.

Any suggestions?

    
asked by Aarón Zúñiga 18.09.2017 в 07:51
source

1 answer

1

I'll explain a little bit like I did.

First, we assign the main controller to the view by adding it in the Scene Builder in the controller section. (lower left corner)

For example, we will call it TabPaneController and in it we will define all the tab that we will use.

@FXML
private Tab tabMonitor;
private MonitorController monitorController;

@FXML
private Tab tabUser;
private UserController userController;

We will have a method that starts all the tabs, for example:

public void initTabPane() {
    createTabMonitor();
    createTabUser();
}

Once this is defined, what I do is a method to launch each tab and assign it to the corresponding tab in it. Important, designing the contents of the tab in an AnchorPane although it is safe to do it in other ways but for me it was more convenient when focusing on the Tab.

public void createTabMonitor() {

    try {
        FXMLLoader loaderMonitor = new FXMLLoader();
        loaderMonitor.setLocation(TabPaneController.class.getResource("AnchorPaneMonitor.fxml");
        AnchorPane anchorPaneMonitor = (AnchorPane) loaderMonitor.load();
        monitorController = loaderMonitor.getController();

        // Para que quede centrado, hago un add en un HBox (por ejemplo)
        HBox hb = new HBox();
        hb.setSpacing(10.0);
        hb.setAligment(Pos.CENTER);
        hb.getChildren().add(anchorPaneMonitor);

        tabMonitor.setContent(hb);

    } catch (IOException e) {
        e.printStackTrace();
    }

We continue with the other tab:

public void createTabUser() {

    try {
        FXMLLoader loaderUser = new FXMLLoader();
        loaderUser.setLocation(TabPaneController.class.getResource("AnchorPaneUser.fxml");
        AnchorPane anchorPaneUser = (AnchorPane) loaderUser.load();
        userController = loaderUser.getController();

        // Para que quede centrado, hago un add en un HBox (por ejemplo)
        HBox hb = new HBox();
        hb.setSpacing(10.0);
        hb.setAligment(Pos.CENTER);
        hb.getChildren().add(anchorPaneUser);

        tabUser.setContent(hb);

    } catch (IOException e) {
        e.printStackTrace();
    }

I hope it works, anything you tell me. Greetings !!!

    
answered by 26.09.2017 в 11:40