JavaFX - 加载 FXML 文件而不加载 FXLoader



我正在试用"新"JavaFX,它运行良好。

现在我正处于一个对我来说无法理解的地步。我有一个用于视图的控制器,我想从主方法加载我的控制器,以便控制器可以加载视图或执行任何它喜欢的操作。

我的问题是,我必须使用FXMLLoader.load()方法加载我的 FXML 文件。FXMLLoader 自己加载控制器。所以实际上,使用我的方法,我将加载控制器两次:我用XController xcontroller = new XController();加载控制器,在该控制器内部,我使用FXMLLoader.load()加载视图,这将再次加载控制器。

我是否必须使用FXMLLoader或者是否可以让我的控制器使用其他方法加载视图?

编辑我想使用表示-抽象-控制 (PAC( 模式(MVC 的变体(,这就是为什么我认为让控制器加载视图是重要的。

主类

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();
}
.....
}
}

如果我理解正确,而不是

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属性才能正常工作。

最新更新