合并多个FXML并为每个文件配备一个控制器

时间:2016-09-27 18:18:36

标签: java javafx fxml

我找到的最好的文章是:How to create multiple javafx controllers with different fxml files?

然而我真的很困惑这是如何工作的。所有示例对于初始学习来说似乎有点过于复杂。

所以这里我有一个简单的helloWorld用于测试目的。正如你在xml中看到的,我有一个容器,菜单和页脚。但是,我希望它们中的所有3个都有单独的控制器和XML文件,然后在课程后合并并显示如下面的XML中所示:

onerror

XML

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;



public class HelloWorld extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        FXMLLoader loader = new FXMLLoader();
        Parent root = loader.setLocation(getClass().getResource("main.fxml"));
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();

        MainController mainController = loader.getController();
    }
}

我真的可以从一个简单的例子中受益。如何将它们保存在单独的文件中并在它们各自保留自己的控制器时合并它们?

1 个答案:

答案 0 :(得分:0)

你可以follow this tutorial

public class MainApp extends Application {

    private Stage primaryStage;
    private BorderPane rootLayout;

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("AddressApp");

        initRootLayout();

        showPersonOverview();
    }

    /**
     * Initializes the root layout.
     */
    public void initRootLayout() {
        try {
            // Load root layout from fxml file.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
            rootLayout = (BorderPane) loader.load();

            // Show the scene containing the root layout.
            Scene scene = new Scene(rootLayout);
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Shows the person overview inside the root layout.
     */
    public void showPersonOverview() {
        try {
            // Load person overview.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainApp.class.getResource("view/PersonOverview.fxml"));
            AnchorPane personOverview = (AnchorPane) loader.load();

            // Set person overview into the center of root layout.
            rootLayout.setCenter(personOverview);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns the main stage.
     * @return
     */
    public Stage getPrimaryStage() {
        return primaryStage;
    }

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

在此示例中,您有两个fxml文件,RootLayout.fxml和PersonOverview.fxml。 您将primarystage的场景设置为(BorderPane)RootLayout.fxml,然后将PersonOverview.fxml添加到BorderPane。