简体   繁体   English

将字段绑定到Javafx中的控制器

[英]Binding Fields to Controllers in Javafx

I have built a scene in using scene builder and I have two textfields that are part of a UI, One for Flavor, one for Topping. 我已经使用场景生成器构建了一个场景,并且有两个文本字段属于UI,一个用于Flavor,一个用于Topping。 In the controller I've annotated each textfield attribute with @FXML. 在控制器中,我用@FXML注释了每个textfield属性。 My question is: how do I associate the fields in the ui to the attributes in the controller class? 我的问题是:如何将ui中的字段与控制器类中的属性相关联?

The java code looks like: Java代码如下所示:

@FXML
private TextField flavorValueField;
@FXML
private TextField toppingValueField;

In the ui, the fields exist in a scene, but really have nothing associated with them that identifies them. 在ui中,字段存在于场景中,但实际上没有任何与它们相关联的标识它们的字段。 Do they need something? 他们需要什么吗? and It's not clear to me, how I assure the binding between the field in the UI and the field in the code occur in the way I want them to. 而且我还不清楚,如何确保UI中的字段与代码中的字段之间的绑定以我希望它们的方式发生。

It's not enough to say, it just works. 仅仅说还行,还不够。 I want to understand how the code knows to bind one field in the UI to an attribute in the code. 我想了解代码如何知道将UI中的一个字段绑定到代码中的属性。 The UI fields are generic. UI字段是通用的。 There's no identifier or classifier that says, this one is flavor and that one is topping. 没有标识符或分类器说,这是一种风味,而一个是一流。 If it just "works" how does the binding happen? 如果只是“有效”,绑定如何发生?

FXMLLoader checks for fx:id attributes in the fxml file. FXMLLoader检查fxml文件中的fx:id属性。 If there is field visible to FXMLLoader in the controller that matches the value of this attribute, FXMLLoader attempts to assign the object created for the element containing the attribute to the field using reflection. 如果控制器中FXMLLoader可见与该属性值匹配的字段,则FXMLLoader尝试使用反射将为包含该属性的元素创建的对象分配给该字段。

Eg 例如

<Button fx:id="foo"/> <!-- this is assigned to the foo field, if possible -->
<Button fx:id="bar"/> <!-- this is assigned to the bar field, if possible -->
@FXML
private Button bar;

@FXML
private Object foo;

Note that the values only become available when fxml is finished loading or in the initialize method, if it exists. 请注意,只有在fxml完成​​加载时或在initialize方法(如果存在)中,这些值才可用。 In the initializer/constructor of the controller they still contain null . 在控制器的初始化器/构造器中,它们仍然包含null

You don't need to do anything more than what you did. 您只需要做些什么就可以了。 It's just @FXML, it'll bind the field in UI with the controller variable. 只是@FXML,它将UI字段与controller变量绑定。 Make sure to bind the scene in UI with the controller in scene builder. 确保将UI中的场景与场景构建器中的控制器绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM