我正在使用 JavaFX 8 开发 Java 8 桌面应用程序。
我在MainApp类(扩展Application类的方法)中有此方法。
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
}
}
并且我要加载的每个布局都使用相同的代码。
有什么方法可以创建一个将类类型作为参数并执行完全相同的工作的方法,例如:
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
}
}
我会这样使用它:
public void showUserLayout() {
genericLayoutLoader("view/userLayout.fxml", AnchorPane, userLayoutController);
}
有什么办法可以实现这种行为?
最佳答案
如果要坚持使用Classs作为参数,则代码应如下所示:
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 = loader.load();
// rootAnchorPane is same for every layout
rootAnchorPane.getChildren().clear();
rootAnchorPane.getChildren().add(chooseUserAndInterval);
Object controller = loader.getController();
fxmlController.getMethod("setMainApp", new Class[] { MainApp.class }).invoke(controller, this);
} catch (IOException e) {
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
public void showUserLayout() {
genericLayoutLoader("view/userLayout.fxml", AnchorPane.class, Controller.class);
}
但是,我仍然建议尝试尽可能使用接口解决此问题。