Bind width and height of dynamically loaded fxml

给你一囗甜甜゛ 提交于 2020-01-11 11:39:07

问题


At the moment I have an issue with dynamically loaded FXML files during runtime. Once they are added to a Pane, they do not resize to use the full widht & height of that pane.

I use this method to load a FXML in my Pane:

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());
    }
}

The FXML gets loaded and works as it should, however I notice the FXML (added as a Node in this case) is not beeing resized to use the full height and width of the content pane (if I open the FXML in preview mode with Scene Builder, it resizes perfectly). Is this a wrong approach or is there an easy way which clearly I did not find?

Thanks in advance!


回答1:


I adjusted the code with the clue Andy gave me. I changed the pContent object to a AnchorPane instead of a Pane. Method that works below:

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());
    }
}

Hint: make sure that in your loaded FXML file you do not use fixed width or height variables.



来源:https://stackoverflow.com/questions/14265697/bind-width-and-height-of-dynamically-loaded-fxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!