I am working on a Java 8 desktop application using JavaFX 8.
I have this method in the MainApp class (the one that extends the Application class).
public void showUserLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/userLayout.fxml"));
AnchorPane userPane = (AnchorPane) loader.load();
rootAnchorPane.getChildren().clear();
rootAnchorPane.getChildren().add(userPane);
userLayoutController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
// Handle Exception
}
}
and I am using the same code for each layout I want to load.
Is there any way to create a method that accepts the class type as a parameter and does the exact same job, for example:
public void genericLayoutLoader(String fxmlFilename, Class rootFXMLElement, Class fxmlController) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource(fxmlFilename));
// Not sure for the Object below
Object chooseUserAndInterval = (rootFXMLElement) loader.load();
// rootAnchorPane is same for every layout
rootAnchorPane.getChildren().clear();
rootAnchorPane.getChildren().add((rootFXMLElement) chooseUserAndInterval);
Object controller = (fxmlController) loader.getController();
((fxmlController)controller).setMainApp(this);
} catch (IOException e) {
// Handle Exception
}
}
I would use it like this:
public void showUserLayout() {
genericLayoutLoader("view/userLayout.fxml", AnchorPane, userLayoutController);
}
Is there any way to achieve this behavior?