如何初始化自定义 javafx 控制器的成员变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20321321/
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
How to initialize member variables of a custom javafx controller?
提问by j will
In the Spring framework, i can use the configuration files to load member variables of a class. Is there a way to do this in javafx with a custom controller or a custom object?
在 Spring 框架中,我可以使用配置文件来加载类的成员变量。有没有办法在 javafx 中使用自定义控制器或自定义对象来做到这一点?
采纳答案by Imran
The @FXML annotation enables the JavaFX objects whose names you defined (fx:id)
to have their references reflectively injected into nonpublic fields in the controller object as the scene graph is loaded from the fxml markup.
@FXML 注释使您定义的名称的 JavaFX 对象能够在(fx:id)
从 fxml 标记加载场景图时将它们的引用反射性地注入到控制器对象的非公共字段中。
You can accomplish something very similar to what you are requesting by defining the values that you want set as class variables in your controller object's class, and then setting the appropriate object properties programmatically (rather than in markup) in the initialize() method of your controller object.
您可以通过在控制器对象的类中定义要设置为类变量的值来完成与您所请求的非常相似的事情,然后在您的控制器对象。
The initialize() method is called (if it is present) after the loading of the scene graph is complete (so all the GUI objects will have been instantiated) but before control has returned to your application's invoking code.
在场景图加载完成后(因此所有 GUI 对象都将被实例化),但在控制返回到应用程序的调用代码之前,将调用 initialize() 方法(如果存在)。
Edit
编辑
You can use @FXML only in Controller which is specifically set in fxml file and only for fields of that class.
您只能在 fxml 文件中专门设置的控制器中使用@FXML,并且只能用于该类的字段。
This is required because these fields would be initialized automatically during creation of that class' object.
这是必需的,因为这些字段将在创建该类的对象期间自动初始化。
public class MyController implements Initializable{
@FXML
Button startButton;
void initialize(java.net.URL location, java.util.ResourceBundle resources) {
startButton.addActionLisetner(...);
}
}
Detailed tutorial is here
详细教程在这里