如何在窗格内加载fxml文件?

Hus*_*ied 13 java javafx javafx-2 fxml

在此输入图像描述

如果我们有一个Stage那么Scene包括2个PaneS中的第一个Pane包含Button与第二Pane是空的,我们可以加载其他FXML这个文件里面第2次Pane

fxml1: VBox
               |_Pane1-->Button
               |_Pane2
///////////////
fxml2: Pane--> Welcome to fxml 2
"when we click the button load the fxml2 inside Pane2 of fxml1"
Run Code Online (Sandbox Code Playgroud)

然后点击

在此输入图像描述


====我终于在尝试后发现了这个作品!====谢谢你们

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

Hus*_*ied 13

我终于在尝试后找到了这个作品!

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


fab*_*ian 5

仅替换控制器类中的字段不会更改场景图。

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;
}
Run Code Online (Sandbox Code Playgroud)

当然,这是假设getClass().getResource("/application/Login2.fxml")产生正确的资源并且不返回null(如果没有给定名称的资源可用,则会发生这种情况)