java 为 Anchor Pane 设置类控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14359763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:00:36  来源:igfitidea点击:

Setting a class Controller for Anchor Pane

javajavafx-2javafxscenebuilder

提问by Rams

When working with JavaFX Scene Builder encountered the following problem...

使用 JavaFX Scene Builder 时遇到以下问题...

Given:

鉴于:

A file fxml, containing description Anchor Pane (fxml formed from Scene Builder);
For Anchor Pane is not specified Controller Class.
This fxml loaded into the Java Application by using FXMLLoader.

一个文件 fxml,包含描述 Anchor Pane(由 Scene Builder 形成的 fxml);
对于 Anchor Pane 没有指定控制器类。
这个 fxml 使用 FXMLLoader 加载到 Java 应用程序中。

Need:

需要:

After downloading the Anchor Pane set the value to Controller Class.
It is necessary for to load the same fxml with different handlers.

下载 Anchor Pane 后,将值设置为 Controller Class。
有必要使用不同的处理程序加载相同的 fxml。

Question:is it possible, and if so - how to implement?

问题:是否有可能,如果有 - 如何实施?

回答by Uluk Biy

The controller class of the loading FXML file can also be set through the Scene Builder. But you want to set it at loading time in the application. To achieve that you should set the controller of the FXMLLoader before the load() method is called:

加载 FXML 文件的控制器类也可以通过 Scene Builder 设置。但是您想在应用程序加载时设置它。为此,您应该在调用 load() 方法之前设置 FXMLLoader 的控制器:

AnchorPane rootPane;
MyController controller = new MyController();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("my.fxml"));
fxmlLoader.setRoot(rootPane);
fxmlLoader.setController(controller);
fxmlLoader.load();