问题
I have a main fxml file with several menus. When the user clicks certain buttons, the content changes and these contents are the seperate fxml files which loads on the main screen. The entire scene doesn't change but only a part of the scene changes instead. Here is a simple prototype of the application which I want to make![enter image description here][1]
https://www.dropbox.com/s/3nildyt004v32vc/fxml%20application.png
回答1:
try this..
AnchorPane pane; // pane where fxml was showing
menu1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
openNewWindow("m1.fxml");
}
});
menu2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
openNewWindow("m2.fxml");
}});
menu3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
openNewWindow("m3.fxml");
}
});
function openNewWindow
public void openNewWindow(String FXMLFile)
{
//ChildNode child;
try {
URL url = getClass().getResource(FXMLFile);
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(url);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
AnchorPane page = (AnchorPane) fxmlLoader.load(url.openStream());
Pane.getChildren().clear();///name of pane where you want to put the fxml
Pane.getChildren().add(page);
}
catch (IOException e) {
e.printStackTrace();
}
}
来源:https://stackoverflow.com/questions/21252007/loading-fxml-files-inside-a-main-fxml-file