1

目前,我在运行时遇到动态加载的 FXML 文件的问题。将它们添加到窗格后,它们不会调整大小以使用该窗格的完整宽度和高度。

我使用此方法在我的窗格中加载 FXML:

public void showContentPane(String sURL){
    //1. sURL can be something like "/GUI/home/master/MasterHome.fxml"
    //2. getContentPane() returns following object: Pane pContent
    try {
        URL url = getClass().getResource(sURL);

        getContentPane().getChildren().clear();
        Node n = (Node) FXMLLoader.load(url, ResourceBundle.getBundle("src.bundles.bundle", getLocale()));

        getContentPane().getChildren().add(n);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

FXML 被加载并按原样工作,但是我注意到 FXML(在这种情况下作为节点添加)没有调整大小以使用内容窗格的完整高度和宽度(如果我在预览模式下使用 Scene 打开 FXML Builder,它可以完美地调整大小)。这是一种错误的方法还是有一种我显然没有找到的简单方法?

提前致谢!

4

1 回答 1

1

我根据安迪给我的线索调整了代码。我将 pContent 对象更改为 AnchorPane 而不是 Pane。方法如下:

public void showContentPane(String sURL){
    //1. sURL can be something like "/GUI/home/master/MasterHome.fxml"
    //2. getContentPane() returns following object: AnchorPane pContent
    try {
        URL url = getClass().getResource(sURL);

        getContentPane().getChildren().clear();

        //create new AnchorPane based on FXML file
        AnchorPane n = (AnchorPane) FXMLLoader.load(url, ResourceBundle.getBundle("src.bundles.bundle", getLocale()));

        //anchor the pane
        AnchorPane.setTopAnchor(n, 0.0);
        AnchorPane.setBottomAnchor(n, 0.0);
        AnchorPane.setLeftAnchor(n, 0.0);
        AnchorPane.setRightAnchor(n, 0.0);

        getContentPane().getChildren().add(n);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

提示:确保在加载的 FXML 文件中不使用固定宽度或高度变量。

于 2013-01-23T10:33:12.337 回答