简体   繁体   English

如何添加 <fx:root> 组件作为FXML中的子组件?

[英]How can I add a <fx:root> component as a child in FXML?

I have a custom component that extends AnchorPane , as in: 我有一个扩展AnchorPane的自定义组件,如下所示:

public class CustomAnchorPane extends AnchorPane { }

I would like to load this within a BorderPane . 我想在BorderPane加载BorderPane If I wanted to load a regular AnchorPane , I would do it as so: (I removed some lines for brevity) 如果我想加载常规的AnchorPane ,我将这样做:(为简洁起见,我删除了一些行)

<BorderPane fx:id="borderpane" ... fx:controller="main.java.Controller">
    <center>
      <AnchorPane fx:id="anchorpane" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
    </center>
 </BorderPane>

I understand the <fx:root> construct is used for reusable/custom components. 我了解<fx:root>构造用于可重用/自定义组件。 I do not understand how to set it as a child of the BorderPane , however, as I believe it must be the root of the FXML file. 我不知道如何将其设置为BorderPane的子级,因为我相信它必须是FXML文件的根。 Thus the following throws an error: 因此,以下内容将引发错误:

<BorderPane fx:id="borderpane" ... fx:controller="main.java.Controller">
    <center>
       <fx:root fx:id="custom_anchorpane" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
    </center>
</BorderPane>

What is the proper way to do this? 正确的方法是什么?

Thanks in advance. 提前致谢。

<fx:root> only makes sense as the root of a fxml, since this is the only place where the parent object of a object created from the fxml is used, but not defined in the fxml itself. <fx:root>仅作为fxml的根有意义,因为这是使用从fxml创建的对象的父对象的唯一位置,但未在fxml本身中定义。

It only makes FXMLLoader use the object passed using setRoot instead of creating a an element for this tag itself. 它仅使FXMLLoader使用通过setRoot传递的对象,而不是为此标签本身创建元素。

Assuming you've properly implemented your custom Node , you can use it the way you'd use any other element: 假设您已经正确实现了自定义Node ,则可以像使用其他任何元素一样使用它:

<BorderPane fx:id="borderpane" ... fx:controller="main.java.Controller">
    <center>
       <CustomAnchorPane fx:id="custom_anchorpane" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
    </center>
</BorderPane>

Note that this requires a suitable import in the processing instructions at the start of the file and the class needs to provide a public constructor taking no parameters. 请注意,这需要在文件开头适当地导入处理指令,并且该类需要提供不带参数的public构造函数。

If you didn't create a custom class yourself, but have a fxml file you want to use in a certain playe, you can also use fx:include : 如果您不是自己创建自定义类,而是拥有要在某个播放器中使用的fxml文件,则还可以使用fx:include

<BorderPane fx:id="borderpane" ... fx:controller="main.java.Controller">
    <center>
       <fx:include source="custom_anchorpane.fxml"/>
    </center>
</BorderPane>

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

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