如何在 Pane 中加载 fxml 文件?

How to load fxml file inside Pane?

如果我们有一个 Stage 那么 Scene 包括 2 Pane 第一个 Pane 包含 Button 而第二个 Pane 是空的 我们可以在第二个 Pane 中加载其他 fxml 文件吗?

fxml1: VBox
               |_Pane1-->Button
               |_Pane2
///////////////
fxml2: Pane--> Welcome to fxml 2
"when we click the button load the fxml2 inside Pane2 of fxml1"

然后点击后


====我终于在尝试后找到了这个作品!====谢谢大家

@FXML Pane secPane;
public void loadFxml (ActionEvent event) {
Pane newLoadedPane =        FXMLLoader.load(getClass().getResource("/application/fxml2.fxml"));
secPane.getChildren().add(newLoadedPane); 
}  

你可以这样实现:

 public void start(Stage primaryStage) throws IOException {
            primaryStage.setTitle("Title");
            primaryStage.setScene(createScene(loadMainPane("path_of_your_fxml")));
            primaryStage.show();

    }

    private Pane loadMainPane(String path) throws IOException {
        FXMLLoader loader = new FXMLLoader();

        Pane mainPane = (Pane) loader.load(
                getClass().getResourceAsStream(path));

        return mainPane;
    }


    private Scene createScene(Pane mainPane) {
        Scene scene = new Scene(mainPane);
      return scene;
    }

然后您可以创建一个单独的 class 调用 Navigation 来存储您所有的 fxml 路径:

public class Navigator {

private final String P1;
private final String P2;
//then you can implement getters...
public String getP1() {
    return P1;
}

public String getP2() {
    return p2;
}

private static FxmlController Controller;

    public static void loadPane(String fxml) {
    try {
        FxmlController.setPane(
                (Node) FXMLLoader.load(Navigator.class.getResource(fxml)));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public Navigator() throws IOException {
    this.P1 = "p1.fxml";
    this.P2 = "p2.fxml";}

然后您可以在您的按钮中加载您的窗格,如下所示:

@FXML
    private void btnAction(ActionEvent event) throws IOException {
    Navigator.load(new Navigator().getP1());
    ..

.

只需替换控制器中的字段 class 不会更改场景图。

secPane只是对场景图中节点的引用。

如果secPane只是一个占位符,您可以在父子列表中替换它:

public void loadFxml (ActionEvent event) {
    // load new pane
    Pane newPane = FXMLLoader.load(getClass().getResource("/application/Login2.fxml"));

    // get children of parent of secPane (the VBox)
    List<Node> parentChildren = ((Pane)secPane.getParent()).getChildren();

    // replace the child that contained the old secPane
    parentChildren.set(parentChildren.indexOf(secPane), newPane);

    // store the new pane in the secPane field to allow replacing it the same way later
    secPane = newPane;
}

这当然假定 getClass().getResource("/application/Login2.fxml") 产生正确的资源而不是 return null(如果没有具有给定名称的资源可用)

经过尝试,我终于找到了这个作品!

@FXML Pane secPane;
public void loadFxml (ActionEvent event)  {
  Pane newLoadedPane =  FXMLLoader.load(getClass().getResource("/application/fxml2.fxml"));
  secPane.getChildren().add(newLoadedPane);
}