我正在使用“新的”JavaFX,并且效果非常好。
现在我处于一个对我来说难以理解的地方。我有一个控制器用于我的视图,我想从主方法加载我的控制器,以便控制器可以加载视图或做任何它喜欢的。
我的问题是,我必须使用FXMLLoader.load()
方法加载我的FXML文件。 FXMLLoader himselfe加载控制器。所以实际上,用我的方法我会加载控制器两次:我用XController xcontroller = new XController();
加载控制器,然后在控制器内加载带有FXMLLoader.load()
的视图,这将再次加载控制器。
我是否必须使用FXMLLoader
或者我可以让控制器使用其他方法加载视图吗?
编辑我想使用Presentation-Abstraction-Control(PAC)模式(MVC的变体),这就是为什么我认为它是重要的,让控制器加载View。
主要班级
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);
}
}
控制器
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();
}
.....
}
}
答案 0 :(得分:2)
如果我理解正确,而不是
root = FXMLLoader.load(
getClass().getResource(
this.initialView.getPath()
)
);
只做
FXMLLoader loader = new FXMLLoader(
getClass().getResource(this.initialView.getPath());
);
loader.setController(this);
root = loader.load();
您需要从FXML文件中删除fx:controller
属性才能生效。