It says tag fx:root
has been added to javafx 2.2, but I don't understand how to use it, although with this sample: http://docs.oracle.com/javafx/2/fxml_get_started/whats_new2.htm
main.xml
<?import javafx.scene.layout.GridPane?>
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<fx:include fx:id="editorPane" source="editor.fxml"/>
</GridPane>
editor.fxml without fx:root
:
<?import javafx.scene.control.TextArea?>
<TextArea fx:id="editor" prefWidth="500" prefHeight="400"
fx:controller="sample.EditorController"
xmlns:fx="http://javafx.com/fxml"/>
editor.fxml with fx:root
:
<fx:root type="javafx.scene.control.TextArea"
fx:id="editor" prefWidth="500" prefHeight="400"
fx:controller="sample.EditorController"
xmlns:fx="http://javafx.com/fxml"/>
Actually, I can't find any difference for the two kinds of code. Do I miss anything?
<fx:root>
provides a solution to the issue of defining a reusable component with FXML.As an example, imagine you want to define a simple custom component consisting of a
TextField
andButton
contained in anHBox
. You need this to be represented by a subclass ofNode
, so you can write code likeThe issue is you need a Java class which is a subclass of
Node
, as well as the FXML. In pure Java (no FXML), you could do this with:Using FXML to define the custom component without the
<fx:root>
element presents a problem, because you need the FXML to be some kind of node, and then another node instance to represent the class wrapping it:and
This results in MyComponent consisting of an HBox wrapping an HBox wrapping the TextField and Button. The additional, redundant HBox is a result of needing one Node for the FXML root and one Node to represent the component.
<fx:root>
gives a mechanism to create the Node as the component (the Java class) and then to instruct the FXML file to use that node as its root:and
Now
MyComponent
has the same structure as the original all-Java version, anHBox
containing aTextField
and aButton
. You can't do this using FXML without the<fx:root>
element.