问题
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