I'm creating a helper class for my JavaFX application as follows:
public class ViewHelper<T extends Parent, U extends Controller> {
private static final String FXML_EXTENSION = ".fxml";
private final Class<? extends Controller> clazz;
private FXMLLoader loader;
private T t;
public ViewHelper(Class<? extends Controller> clazz) throws IOException {
this.clazz = clazz;
this.load();
}
private void load() throws IOException {
this.loader = new FXMLLoader(fxmlUrl());
this.t = this.loader.load();
}
private URL fxmlUrl() {
return clazz.getResource(clazz.getSimpleName() + FXML_EXTENSION);
}
public T component() {
return t;
}
public U controller() {
return loader.getController();
}
}
The usage is:
var viewHelper = new ViewHelper<BorderPane, MainController>(MainController.class);
BorderPane borderPane = viewHelper.component();
MainController mainController = viewHelper.controller();
It actually works and achieves what I want. However, it irritates me to see I have to pass MainController
twice when at all times they are the same. No instance that they are not the same. How can I avoid one of them during instance creation of ViewHelper
?
Instead of:
var viewHelper = new ViewHelper<BorderPane, MainController>(MainController.class);
I would prefer something like:
var viewHelper = new ViewHelper<BorderPane>(MainController.class);
or:
var viewHelper = new ViewHelper<BorderPane, MainController>();
Thanks for any help.
You can add a static method to be called instead of the constructor.
public static <T extends Parent, U extends Controller> ViewHelper<T, U> of(Class<T> componentType, Class<U> controllerType) throws IOException {
return new ViewHelper<T, U>(controllerType);
}
You then call it like this:
var viewHelper = ViewHelper.of(BorderPane.class, MainController.class);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.