I am experementing with the "new" JavaFX and it worked very well.
Now I am at a point which is incomprehensible for me. I have a Controller for my View and I want to load my Controller from a main-method so the controller can load a view or do whatever it likes.
My problem ist, that I have to load my FXML-File with the FXMLLoader.load()
method. The FXMLLoader himselfe loads the controller. So in fact, with my method I will load the controller two times: I load the controller with XController xcontroller = new XController();
and inside that controller I load te view with the FXMLLoader.load()
which will load the controller again.
do I have to use FXMLLoader
or can I let my controller load the view with an other method?
edit I want to use the Presentation-Abstraction-Control (PAC) Pattern (variation of MVC), that's why I think it's importand to let the controller load the View.
the main class
public class Main extends Application
{
Override
public void start(Stage primaryStage)
{
LoginController loginController = null;
try
{
loginController = new LoginController();
loginController.loadSceneInto(primaryStage);
primaryStage.show();
}
.......
public static void main(String[] args)
{
launch(args);
}
}
the controller
public class LoginController
{
.....
public void loadSceneInto(Stage stage) throws IOException
{
this.stage = stage;
Scene scene = null;
Pane root = null;
try
{
root = FXMLLoader.load(
getClass().getResource(
this.initialView.getPath()
)
);
scene = new Scene(root, initialWidth, initialHeight);
this.stage.setTitle(this.stageTitle);
this.stage.setScene(scene);
this.centralizeStage();
}
.....
}
}
If I understand correctly, instead of
root = FXMLLoader.load(
getClass().getResource(
this.initialView.getPath()
)
);
Just do
FXMLLoader loader = new FXMLLoader(
getClass().getResource(this.initialView.getPath());
);
loader.setController(this);
root = loader.load();
You will need to remove the fx:controller
attribute from the FXML file for this to work.