< prev index next >

modules/javafx.fxml/src/main/docs/javafx/fxml/doc-files/introduction_to_fxml.html

Print this page
rev 10359 : 8170701: Update FXML documentation for setAccessible
Reviewed-by:
   1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2 
   3 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">    
   4 <head>
   5 <link href="fxml.css" rel="stylesheet"/>    
   6 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
   7 <title>Introduction to FXML | JavaFX 9</title>
   8 <meta name="description" content="The document introduces FXML, an XML-based declarative markup language for defining user interfaces in JavaFX 9 applications."/>
   9 <meta name="keywords" content="JavaFX 9, FXML, JavaFX GUI development, web development, Java application development, GUI applications, rich internet applications, RIA, expressive content"/>
  10 </head>
  11 <body>
  12 
  13 <div class="fx-code-header">
  14 <div class="version"><br/>Release: JavaFX 9</div>
  15 </div>
  16 
  17 <h1>Introduction to FXML</h1>
  18 <p class="subtitle">Last updated: 9/10/2013</p>
  19 
  20 <h2>Contents</h2>
  21 <ul class="contents">
  22 <li><a href="#overview">Overview</a></li>
  23 <li>
  24     <a href="#elements">Elements</a>
  25     <ul>
  26     <li>
  27         <a href="#class_instance_elements">Class Instance Elements</a>
  28         <ul>
  29         <li><a href="#instance_declaration_elements">Instance Declarations</a></li>
  30         <li><a href="#include_elements">&lt;fx:include&gt;</a></li>
  31         <li><a href="#constant_elements">&lt;fx:constant&gt;</a></li>
  32         <li><a href="#reference_elements">&lt;fx:reference&gt;</a></li>
  33         <li><a href="#copy_elements">&lt;fx:copy&gt;</a></li>
  34         <li><a href="#root_elements">&lt;fx:root&gt;</a></li>
  35         </ul>
  36     </li>
  37 
  38     <li>


  97 <p>This document introduces the FXML markup language and explains how it can be used to simplify development of JavaFX applications.</p>
  98 
  99 <h2><a name="elements">Elements</a></h2>
 100 <p>In FXML, an XML element represents one of the following:</p>
 101 <ul>
 102 <li>A class instance</li>
 103 <li>A property of a class instance</li>
 104 <li>A "static" property</li>
 105 <li>A "define" block</li>
 106 <li>A block of script code</li>
 107 </ul>
 108 
 109 <p>Class instances, instance properties, static properties, and define blocks are discussed in this section below. Scripting is discussed in a later section.</p>
 110 
 111 <h3><a name="class_instance_elements">Class Instance Elements</a></h3>
 112 <p>Class instances can be constructed in FXML in several ways. The most common is via instance declaration elements, which simply create a new instance of a class by name. Other ways of creating class instances include referencing existing values, copying existing values, and including external FXML files. Each is discussed in more detail below.</p>
 113 
 114 <h4><a name="instance_declaration_elements">Instance Declarations</a></h4>
 115 <p><assert id="instance_declaration" group="instance_declarations">If an element's tag is considered an instance declaration if the tag begins with uppercase letter (and the class is imported)</assert> or, as in Java, <assert id="fully_qualified_name" group="instance_declarations">it denotes a fully-qualified (including the package name) name of a class.</assert> When the FXML loader (also introduced later) encounters such an element, it creates an instance of that class.</p>
 116 
 117 <p><assert id="import" group="instance_declarations">Importing a class is done using the "import" processing instruction (PI). For example, the following PI imports the <span class="code">javafx.scene.control.Label</span> class into the current FXML document’s namespace:</p>
 118 
 119 <pre class="code">
 120 &lt;?import javafx.scene.control.Label?&gt;
 121 </pre>
 122 
 123 <p>This PI imports all classes from the javafx.scene.control package into the current namespace:</p>
 124 
 125 <pre class="code">
 126 &lt;?import javafx.scene.control.*?&gt;
 127 </pre>
 128 </assert>
 129 
 130 <p><assert id="instantiation_java_bean" group="instance_declarations">Any class that adheres to JavaBean constructor and property naming conventions can be readily instantiated and configured using FXML.</assert> The following is a simple but complete example that creates an instance of <span class="code">javafx.scene.control.Label</span> and sets its "text" property to "Hello, World!":</p>
 131 
 132 <pre class="code">
 133 &lt;?import javafx.scene.control.Label?&gt;
 134 &lt;Label text="Hello, World!"/&gt;
 135 </pre>
 136 
 137 <p>Note that the <span class="code">Label</span>’s "text" property in this example is set using an XML attribute. Properties can also be set using nested property elements. Property elements are discussed in more detail later in this section. Property attributes are discussed in a later section.</p>
 138 
 139 <p>Classes that don't conform to Bean conventions can also be constructed in FXML, using an object called a "builder". Builders are discussed in more detail later.</p>
 140 
 141 <h5>Maps</h5>
 142 <p>Internally, the FXML loader uses an instance of <span class="code">com.sun.javafx.fxml.BeanAdapter</span> to wrap an instantiated object and invoke its setter methods. This (currently) private class implements the <span class="code">java.util.Map</span> interface and allows a caller to get and set Bean property values as key/value pairs.</p>
 143 
 144 <p><assert id="map_instantiaton" group="instance_declarations">If an element represents a type that already implements <span class="code">Map</span> (such as <span class="code">java.util.HashMap</span>), it is not wrapped and its <span class="code">get()</span> and <span class="code">put()</span> methods are invoked directly.</assert> For example, the following FXML creates an instance of <span class="code">HashMap</span> and sets its "foo" and "bar" values to "123" and "456", respectively:
 145 
 146 <pre class="code">
 147 &lt;HashMap foo="123" bar="456"/&gt;
 148 </pre>
 149 
 150 <h5>fx:value</h5>
 151 <p><assert id="instantiation_no_default_constructor" group="instance_declarations">The <span class="code">fx:value</span> attribute can be used to initialize an instance of a type that does not have a default constructor but provides a static <span class="code">valueOf(String)</span> method.</assert> For example, <span class="code">java.lang.String</span> as well as each of the primitive wrapper types define a <span class="code">valueOf()</span> method and can be constructed in FXML as follows:</p>
 152 
 153 <pre class="code">
 154 &lt;String fx:value="Hello, World!"/&gt;
 155 &lt;Double fx:value="1.0"/&gt;
 156 &lt;Boolean fx:value="false"/&gt;
 157 </pre>
 158 
 159 <p>Custom classes that define a static <span class="code">valueOf(String)</span> method can also be constructed this way.</p>
 160 
 161 <h5>fx:factory</h5>
 162 <p><assert id="instantiation_factory" group="instance_declarations">The <span class="code">fx:factory</span> attribute is another means of creating objects whose classes do not have a default constructor. The value of the attribute is the name of a static, no-arg factory method for producing class instances.</assert> For example, the following markup creates an instance of an observable array list, populated with three string values:</p>
 163 
 164 <pre class="code">
 165 &lt;FXCollections fx:factory="observableArrayList"&gt;
 166     &lt;String fx:value="A"/&gt;
 167     &lt;String fx:value="B"/&gt;
 168     &lt;String fx:value="C"/&gt;
 169 &lt;/FXCollections&gt;
 170 </pre>
 171 
 172 <h5>Builders</h5>
 173 <p><assert id="instantiation_builder" group="instance_declarations">A third means of creating instances of classes that do not conform to Bean conventions (such as those representing immutable values) is a "builder".</assert> The builder design pattern delegates object construction to a mutable helper class (called a "builder") that is responsible for manufacturing instances of the immutable type.</p>
 174 
 175 <p>Builder support in FXML is provided by two interfaces. The <span class="code">javafx.util.Builder</span> interface defines a single method named <span class="code">build()</span> which is responsible for constructing the actual object:</p>
 176 
 177 <pre class="code">
 178 public interface Builder&lt;T&gt; {
 179     public T build();
 180 }
 181 </pre>
 182 
 183 <p>A <span class="code">javafx.util.BuilderFactory</span> is responsible for producing builders that are capable of instantiating a given type:</p>
 184 
 185 <pre class="code">
 186 public interface BuilderFactory {
 187     public Builder&lt;?&gt; getBuilder(Class&lt;?&gt; type);
 188 }
 189 </pre>
 190 
 191 <p>A default builder factory, <span class="code">JavaFXBuilderFactory</span>, is provided in the <span class="code">javafx.fxml</span> package. This factory is capable of creating and configuring most immutable JavaFX types. For example, the following markup uses the default builder to create an instance of the immutable <span class="code">javafx.scene.paint.Color</span> class:
 192 
 193 <pre class="code">
 194 &lt;Color red="1.0" green="0.0" blue="0.0"/&gt;
 195 </pre>
 196 
 197 <p>Note that, unlike Bean types, which are constructed when the element's start tag is processed, objects constructed by a builder are not instantiated until the element's closing tag is reached. This is because all of the required arguments may not be available until the element has been fully processed. For example, the Color object in the preceding example could also be written as:</p>
 198 
 199 <pre class="code">
 200 &lt;Color&gt;
 201     &lt;red&gt;1.0&lt;/red&gt;
 202     &lt;green&gt;0.0&lt;/green&gt;
 203     &lt;blue&gt;0.0&lt;/blue&gt;
 204 &lt;/Color&gt;
 205 </pre>
 206 
 207 <p>The <span class="code">Color</span> instance cannot be fully constructed until all three of the color components are known.</p>
 208 
 209 <p>When processing markup for an object that will be constructed by a builder, the <span class="code">Builder</span> instances are treated like value objects - if a <span class="code">Builder</span> implements the <span class="code">Map</span> interface, the <span class="code">put()</span> method is used to set the builder's attribute values. Otherwise, the builder is wrapped in a <span class="code">BeanAdapter</span> and its properties are assumed to be exposed via standard Bean setters.</p>
 210 
 211 <h4><a name="include_elements">&lt;fx:include&gt;</a></h4>
 212 <p>The <span class="code">&lt;fx:include&gt;</span> tag creates an object from FXML markup defined in another file. It is used as follows:</p>
 213 
 214 <pre class="code">
 215 &lt;fx:include source="<span class="variable">filename</span>"/&gt;
 216 </pre>
 217 
 218 <p>where <span class="variable">filename</span> is the name of the FXML file to include. <assert id="include_leading_slash_character" group="instance_declarations">Values that begin with a leading slash character are treated as relative to the classpath.</assert> <assert id="include_no_leading_slash_character" group="instance_declarations">Values with no leading slash are considered relative to the path of the current document.</assert></p>
 219 
 220 <p>For example, given the following markup:</p>
 221 
 222 <pre class="code">
 223 &lt;?import javafx.scene.control.*?&gt;
 224 &lt;?import javafx.scene.layout.*?&gt;
 225 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 226     &lt;children&gt;
 227         &lt;fx:include source="my_button.fxml"/&gt;
 228     &lt;/children&gt;
 229 &lt;/VBox&gt;
 230 </pre>
 231 
 232 <p>If <span class="filename">my_button.fxml</span> contains the following:
 233 
 234 <pre class="code">
 235 &lt;?import javafx.scene.control.*?&gt;
 236 &lt;Button text="My Button"/&gt;
 237 </pre>
 238 
 239 <p>the resulting scene graph would contain a <span class="code">VBox</span> as a root object with a single <span class="code">Button</span> as a child node.</p>
 240 
 241 <p>Note the use of the "fx" namespace prefix. This is a reserved prefix that defines a number of elements and attributes that are used for internal processing of an FXML source file. It is generally declared on the root element of a FXML document. Other features provided by the "fx" namespace are described in the following sections.</p>
 242 
 243 <p><span class="code">&lt;fx:include&gt;</span> also supports attributes for specifying the name of the resource bundle that should be used to localize the included content, as well as the character set used to encode the source file. Resource resolution is discussed in a later section.</p>
 244 
 245 <pre class="code">
 246 &lt;fx:include source="<span class="variable">filename</span>" resources="<span class="variable">resource_file</span>" charset="utf-8"/&gt;
 247 </pre>
 248 
 249 <h4><a name="constant_elements">&lt;fx:constant&gt;</a></h4>
 250 <p><assert id="constant" group="instance_declarations">The <span class="code">&lt;fx:constant&gt;</span> element creates a reference to a class constant.</assert> For example, the following markup sets the value of the "minWidth" property of a<span class="code">Button</span> instance to the value of the <span class="code">NEGATIVE_INFINITY</span> constant defined by the <span class="code">java.lang.Double</span> class:</p>
 251 
 252 <pre class="code">
 253 &lt;Button&gt;
 254     &lt;minHeight&gt;&lt;Double fx:constant="NEGATIVE_INFINITY"/&gt;&lt;/minHeight&gt;
 255 &lt;/Button&gt;
 256 </pre>
 257 
 258 <h4><a name="reference_elements">&lt;fx:reference&gt;</a></h4>
 259 <p><assert id="reference" group="instance_declarations">The <span class="code">&lt;fx:reference&gt;</span> element creates a new reference to an existing element.</assert> Wherever this tag appears, it will effectively be replaced by the value of the named element. It is used in conjunction with either the <span class="code">fx:id</span> attribute or with a script variables, both of which are discussed in more detail in later sections. The "source" attribute of the <span class="code">&lt;fx:reference&gt;</span> element specifies the name of the object to which the new element will refer.</p>
 260 
 261 <p>For example, the following markup assigns a previously-defined <span class="code">Image</span> instance named "myImage" to the "image" property of an <span class="code">ImageView</span> control:</p>
 262 
 263 <pre class="code">
 264 &lt;ImageView&gt;
 265     &lt;image&gt;
 266         &lt;fx:reference source="myImage"/&gt;
 267     &lt;/image&gt;
 268 &lt;/ImageView&gt;
 269 </pre>
 270 
 271 <p>Note that, since it is also possible to dereference a variable using the attribute variable resolution operator (discussed later in the <a href="#attributes">Attributes</a> section), <span class="code">fx:reference</span> is generally only used when a reference value must be specified as an element, such as when adding the reference to a collection:</p>
 272 
 273 <pre class="code">
 274 &lt;ArrayList&gt;
 275     &lt;fx:reference source="element1"/&gt;
 276     &lt;fx:reference source="element2"/&gt;
 277     &lt;fx:reference source="element3"/&gt;
 278 &lt;/ArrayList&gt;
 279 </pre>
 280 
 281 <p>For most other cases, using an attribute is simpler and more concise.</p>
 282 
 283 <h4><a name="copy_elements">&lt;fx:copy&gt;</a></h4>
 284 <p><assert id="copy" group="instance_declarations">The <span class="code">&lt;fx:copy&gt;</span> element creates a copy of an existing element.</assert> Like <span class="code">&lt;fx:reference&gt;</span>, it is used with the fx:id attribute or a script variable. The element's "source" attribute specifies the name of the object that will be copied. The source type must define a copy constructor that will be used to construct the copy from the source value.</p>
 285 
 286 <p>At the moment, no JavaFX platform classes provide such a copy constructor, so this element is provided primarily for use by application developers. This may change in a future release.</p>
 287 
 288 <h4><a name="root_elements">&lt;fx:root&gt;</a></h4>
 289 <p><assert id="root" group="instance_declarations">The <span class="code">&lt;fx:root&gt;</span> element creates a reference to a previously defined root element. It is only valid as the root node of an FXML document.</assert> <span class="code">&lt;fx:root&gt;</span> is used primarily when creating custom controls that are backed by FXML markup. This is discussed in more detail in the <a href="#fxmlloader">FXMLLoader</a> section.</p>
 290 
 291 <h3><a name="property_elements">Property Elements</a></h3>
 292 <p>Elements whose tag names begin with a lowercase letter represent object properties. A property element may represent one of the following:</p>
 293 
 294 <ul>
 295 <li>A property setter</li>
 296 <li>A read-only list property</li>
 297 <li>A read-only map property</li>
 298 </ul>
 299 
 300 <h4><a name="property_setter_elements">Property Setters</a></h4>
 301 <p><assert id="property_setter" group="property_elements">If an element represents a property setter, the contents of the element (which must be either a text node or a nested class instance element) are passed as the value to the setter for the property.</assert></p>
 302 
 303 <p>For example, the following FXML creates an instance of the <span class="code">Label</span> class and sets the value of the label's "text" property to "Hello, World!":</p>
 304 
 305 <pre class="code">
 306 &lt;?import javafx.scene.control.Label?&gt;
 307 &lt;Label&gt;
 308     &lt;text&gt;Hello, World!&lt;/text&gt;
 309 &lt;/Label&gt;
 310 </pre>
 311 
 312 <p>This produces the same result as the earlier example which used an attribute to set the "text" property:</p>
 313 
 314 <pre class="code">
 315 &lt;?import javafx.scene.control.Label?&gt;
 316 &lt;Label text="Hello, World!"/&gt;
 317 </pre>
 318 
 319 <p>Property elements are generally used when the property value is a complex type that can't be represented using a simple string-based attribute value, or when the character length of the value is so long that specifying it as an attribute would have a negative impact on readability.</p>
 320 
 321 <h5>Type Coercion</h5>
 322 <p><assert id="coercion" group="property_elements">FXML uses "type coercion" to convert property values to the appropriate type as needed.</assert> Type coercion is required because the only data types supported by XML are elements, text, and attributes (whose values are also text). However, Java supports a number of different data types including built-in primitive value types as well as extensible reference types.</p>
 323 
 324 <p>The FXML loader uses the <span class="code">coerce()</span> method of <span class="code">BeanAdapter</span> to perform any required type conversions. This method is capable of performing basic primitive type conversions such as <span class="code">String</span> to <span class="code">boolean</span> or <span class="code">int</span> to <span class="code">double</span>, and will also convert <span class="code">String</span> to <span class="code">Class</span> or <span class="code">String</span> to <span class="code">Enum</span>. Additional conversions can be implemented by defining a static <span class="code">valueOf()</span> method on the target type.</p>
 325 
 326 <h4><a name="read_only_list_property_elements">Read-Only List Properties</a></h4>
 327 <p><assert id="read_only_list_property" group="property_elements">A read-only list property is a Bean property whose getter returns an instance of <span class="code">java.util.List</span> and has no corresponding setter method. The contents of a read-only list element are automatically added to the list as they are processed.</assert></p>
 328 
 329 <p>For example, the "children" property of <span class="code">javafx.scene.Group</span> is a read-only list property representing the group's child nodes:</p>
 330 
 331 <pre class="code">
 332 &lt;?import javafx.scene.*?&gt;
 333 &lt;?import javafx.scene.shape.*?&gt;
 334 &lt;Group xmlns:fx="http://javafx.com/fxml"&gt;
 335     &lt;children&gt;
 336         &lt;Rectangle fx:id="rectangle" x="10" y="10" width="320" height="240"
 337             fill="#ff0000"/&gt;
 338         ...
 339     &lt;/children&gt;
 340 &lt;/Group&gt;
 341 </pre>
 342 
 343 <p>As each sub-element of the <span class="code">&lt;children&gt;</span> element is read, it is added to the list returned by <span class="code">Group#getChildren()</span>.
 344 
 345 <h4><a name="read_only_map_property_elements">Read-Only Map Properties</a></h4>
 346 <p><assert id="read_only_map_property" group="property_elements">A read-only map property is a bean property whose getter returns an instance of <span class="code">java.util.Map</span> and has no corresponding setter method. The attributes of a read-only map element are applied to the map when the closing tag is processed.</assert></p>
 347 
 348 <p>The "properties" property of <span class="code">javafx.scene.Node</span> is an example of a read-only map property. The following markup sets the "foo" and "bar" properties of a <span class="code">Label</span> instance to "123" and "456", respectively:</p>
 349 
 350 <pre class="code">
 351 &lt;?import javafx.scene.control.*?&gt;
 352 &lt;Button&gt;
 353     &lt;properties foo="123" bar="456"/&gt;
 354 &lt;/Button&gt;
 355 </pre>
 356 
 357 <p><assert id="read_only_property_type_treating" group="property_elements">Note that a read-only property whose type is neither a <span class="code">List</span> nor a <span class="code">Map</span> will be treated as if it were a read-only map. The return value of the getter method will be wrapped in a <span class="code">BeanAdapter</span> and can be used in the same way as any other read-only map.</assert></p>
 358 
 359 <h4><a name="default_properties">Default Properties</a></h4>
 360 <p><assert id="default_property" group="property_elements">A class may define a "default property" using the <span class="code">@DefaultProperty</span> annotation defined in the <span class="code">javafx.beans</span> package. If present, the sub-element representing the default property can be omitted from the markup.</assert></p>
 361 
 362 <p>For example, since <span class="code">javafx.scene.layout.Pane</span> (the superclass of <span class="code">javafx.scene.layout.VBox</span>) defines a default property of "children", a <span class="code">&lt;children&gt;</span> element is not required; the loader will automatically add the sub-elements of the <span class="code">VBox</span> to the container's "children" collection:</p>
 363 
 364 <pre class="code">
 365 &lt;?import javafx.scene.*?&gt;
 366 &lt;?import javafx.scene.shape.*?&gt;
 367 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 368     &lt;Button text="Click Me!"/&gt;
 369     ...
 370 &lt;/VBox&gt;
 371 </pre>
 372 
 373 <p>Note that default properties are not limited to collections. If an element's default property refers to a scalar value, any sub-element of that element will be set as the value of the property.</p>
 374 
 375 <p>For example, since <span class="code">javafx.scene.control.ScrollPane</span> defines a default property of "content", a scroll pane containing a <span class="code">TextArea</span> as its content can be specified as follows:
 376 
 377 <pre class="code">
 378 &lt;ScrollPane&gt;
 379     &lt;TextArea text="Once upon a time..."/&gt;
 380 &lt;/ScrollPane&gt;
 381 </pre>
 382 
 383 <p>Taking advantage of default properties can significantly reduce the verbosity of FXML markup.</p>
 384 
 385 <h3><a name="static_property_elements">Static Properties</a></h3>
 386 <p><assert id="static_property" group="elements">An element may also represent a "static" property (sometimes called an "attached property"). Static properties are properties that only make sense in a particular context. They are not intrinsic to the class to which they are applied, but are defined by another class (often, the parent container of a control).</assert></p>
 387 
 388 <p>Static properties are prefixed with the name of class that defines them. For example, The following FXML invokes the static setter for <span class="code">GridPane</span>'s "rowIndex" and "columnIndex" properties:</p>
 389 
 390 <pre class="code">
 391 &lt;GridPane&gt;
 392     &lt;children&gt;
 393         &lt;Label text="My Label"&gt;
 394             &lt;GridPane.rowIndex&gt;0&lt;/GridPane.rowIndex&gt;
 395        &lt;GridPane.columnIndex&gt;0&lt;/GridPane.columnIndex&gt;
 396         &lt;/Label&gt;
 397     &lt;/children&gt;
 398 &lt;/TabPane&gt;
 399 </pre>
 400 
 401 <p>This translates roughly to the following in Java:</p>
 402 
 403 <pre class="code">
 404 GridPane gridPane = new GridPane();
 405 
 406 Label label = new Label();
 407 label.setText("My Label");
 408 
 409 GridPane.setRowIndex(label, 0);
 410 GridPane.setColumnIndex(label, 0);
 411 
 412 gridPane.getChildren().add(label);
 413 </pre>
 414 
 415 The calls to <span class="code">GridPane#setRowIndex()</span> and <span class="code">GridPane#setColumnIndex()</span> "attach" the index data to the <span class="code">Label</span> instance. <span class="code">GridPane</span> then uses these during layout to arrange its children appropriately. Other containers, including <span class="code">AnchorPane</span>, <span class="code">BorderPane</span>, and <span class="code">StackPane</span>, define similar properties.</p>
 416 
 417 <p>As with instance properties, static property elements are generally used when the property value cannot be efficiently represented by an attribute value. Otherwise, static property attributes (discussed in a later section) will generally produce more concise and readable markup.</p>
 418 
 419 <h3><a name="define_elements">Define Blocks</a></h3>
 420 <p><assert id="define" group="elements">The <span class="code">&lt;fx:define&gt;</span> element is used to create objects that exist outside of the object hierarchy but may need to be referred to elsewhere.</assert></p>
 421 
 422 <p>For example, when working with radio buttons, it is common to define a <span class="code">ToggleGroup</span> that will manage the buttons' selection state. This group is not part of the scene graph itself, so should not be added to the buttons' parent. A define block can be used to create the button group without interfering with the overall structure of the document:</p>
 423 
 424 <pre class="code">
 425 &lt;VBox&gt;
 426     &lt;fx:define&gt;
 427         &lt;ToggleGroup fx:id="myToggleGroup"/&gt;
 428     &lt;/fx:define&gt;
 429     &lt;children&gt;
 430         &lt;RadioButton text="A" toggleGroup="$myToggleGroup"/&gt;
 431         &lt;RadioButton text="B" toggleGroup="$myToggleGroup"/&gt;
 432         &lt;RadioButton text="C" toggleGroup="$myToggleGroup"/&gt;
 433     &lt;/children&gt;
 434 &lt;/VBox&gt;
 435 </pre>
 436 
 437 <p>Elements in define blocks are usually assigned an ID that can be used to refer to the element's value later. IDs are discussed in more detail in later sections.</p>
 438 
 439 <h2><a name="attributes">Attributes</a></h2>
 440 <p>An attribute in FXML may represent one of the following:</p>
 441 <ul>
 442 <li>A property of a class instance</li>
 443 <li>A "static" property</li>
 444 <li>An event handler</li>
 445 </ul>
 446 
 447 <p>Each are discussed in more detail in the following sections.</p>
 448 
 449 <h3><a name="instance_property_attributes">Instance Properties</a></h3>
 450 <p><assert id="instance_properties" group="instance_properties">Like property elements, attributes can also be used to configure the properties of a class instance.</assert> For example, the following markup creates a <span class="code">Button</span> whose text reads "Click Me!":</p>
 451 
 452 <pre class="code">
 453 &lt;?import javafx.scene.control.*?&gt;
 454 &lt;Button text="Click Me!"/&gt;
 455 </pre>
 456 
 457 <p><assert id="attributes_type_coercion" group="instance_properties">As with property elements, property attributes support type coercion.</assert> When the following markup is processed, the "x", "y", "width", and "height" values will be converted to doubles, and the "fill" value will be converted to a <span class="code">Color</span>:</p>
 458 
 459 <pre class="code">
 460 &lt;Rectangle fx:id="rectangle" x="10" y="10" width="320" height="240"
 461     fill="#ff0000"/&gt;
 462 </pre>
 463 
 464 <p>Unlike property elements, which are applied as they are processed, property attributes are not applied until the closing tag of their respective element is reached. This is done primarily to facilitate the case where an attribute value depends on some information that won't be available until after the element's content has been completely processed (for example, the selected index of a <span class="code">TabPane</span> control, which can't be set until all of the tabs have been added).</p>
 465 
 466 <p>Another key difference between property attributes and property elements in FXML is that attributes support a number of "resolution operators" that extend their functionality. The following operators are supported and are discussed in more detail below:</p>
 467 
 468 <ul>
 469 <li>Location resolution</li>
 470 <li>Resource resolution</li>
 471 <li>Variable resolution</li>
 472 </ul>
 473 
 474 <h4><a name="location_resolution">Location Resolution</a></h4>
 475 <p><assert id="location_resolution" group="instance_properties">As strings, XML attributes cannot natively represent typed location information such as a URL. However, it is often necessary to specify such locations in markup; for example, the source of an image resource. The location resolution operator (represented by an "@" prefix to the attribute value) is used to specify that an attribute value should be treated as a location relative to the current file rather than a simple string.</assert></p>
 476 
 477 <p>For example, the following markup creates an ImageView and populates it with image data from <span class="filename">my_image.png</span>, which is assumed to be located at a path relative to the current FXML file:</p>
 478 
 479 <pre class="code">
 480 &lt;ImageView&gt;
 481     &lt;image&gt;
 482         &lt;Image url="@my_image.png"/&gt;
 483     &lt;/image&gt;
 484 &lt;/ImageView&gt;
 485 </pre>
 486 
 487 <p>Since <span class="code">Image</span> is an immutable object, a builder is required to construct it. Alternatively, if <span class="code">Image</span> were to define a <span class="code">valueOf(URL)</span> factory method, the image view could be populated as follows:</p>
 488 
 489 <pre class="code">
 490 &lt;ImageView image="@my_image.png"/&gt;
 491 </pre>
 492 
 493 <p>The value of the "image" attribute would be converted to a URL by the FXML loader, then coerced to an <span class="code">Image</span> using the <span class="code">valueOf()</span> method.</p>
 494 
 495 <p>Note that whitespace values in the URL must be encoded; for example, to refer to a file named "My Image.png", the FXML document should contain the following:</p>
 496 
 497 <pre class="code">
 498 &lt;Image url="@My%20Image.png"/&gt;
 499 </pre>
 500 
 501 <p>rather than:</p>
 502 
 503 <pre class="code">
 504 &lt;Image url="@My Image.png"/&gt;
 505 </pre>
 506 
 507 <h4><a name="resource_resolution">Resource Resolution</a></h4>
 508 <assert id="resource_resolution" group="instance_properties">
 509 <p>In FXML, resource substitution can be performed at load time for localization purposes. When provided with an instance of <span class="code">java.util.ResourceBundle</span>, the FXML loader will replace instances of resource names with their locale-specific values. Resource names are identified by a "%" prefix, as shown below:</p>
 510 
 511 <pre class="code">
 512 &lt;Label text="%myText"/&gt;
 513 </pre>
 514 
 515 <p>If the loader is given a resource bundle defined as follows:</p>
 516 
 517 <pre class="code">
 518 myText = This is the text!
 519 </pre>
 520 </assert>
 521 
 522 <p>the output of the FXML loader would be a <span class="code">Label</span> instance containing the text "This is the text!".</p>
 523 
 524 <h4><a name="variable_resolution">Variable Resolution</a></h4>
 525 <p><assert id="variable_resolution" group="instance_properties">An FXML document defines a variable namespace in which named elements and script variables may be uniquely identified. The variable resolution operator allows a caller to replace an attribute value with an instance of a named object before the corresponding setter method is invoked. Variable references are identified by a "$" prefix</assert>, as shown below:</p>
 526 
 527 <pre class="code">
 528 &lt;fx:define&gt;
 529     &lt;ToggleGroup fx:id="myToggleGroup"/&gt;
 530 &lt;/fx:define&gt;
 531 ...
 532 &lt;RadioButton text="A" toggleGroup="$myToggleGroup"/&gt;
 533 &lt;RadioButton text="B" toggleGroup="$myToggleGroup"/&gt;
 534 &lt;RadioButton text="C" toggleGroup="$myToggleGroup"/&gt;
 535 </pre>
 536 
 537 <p><assert id="assigning_id" group="instance_properties">Assigning an <span class="code">fx:id</span> value to an element creates a variable in the document's namespace that can later be referred to by variable dereference attributes, such as the "toggleGroup" attribute shown above, or in script code, discussed in a later section. Additionally, if the object's type defines an "id" property, this value will also be passed to the objects <span class="code">setId()</span> method.</assert></p>
 538 
 539 <h4><a name="escape_sequences">Escape Sequences</a></h4>
 540 
 541 <p><assert id="escape_sequences" group="instance_properties">If the value of an attribute begins with one of the resource resolution prefixes, the character can be escaped by prepending it with a leading backslash ("\") character.</assert> For example, the following markup creates a <span class="code">Label</span> instance whose text reads "$10.00":</p>
 542 
 543 <pre class="code">
 544 &lt;Label text="\$10.00"/&gt;
 545 </pre>
 546 
 547 <h4><a name="expression_binding">Expression Binding</a></h4>
 548 <p>Attribute variables as shown above are resolved once at load time. Later updates to the variables value are not automatically reflected in any properties to which the value was assigned. In many cases, this is sufficient; however, it is often convenient to "bind" a property value to a variable or expression such that changes to the variable are automatically propagated to the target property. Expression bindings can be used for this purpose.</p>
 549 
 550 <p><assert id="expression_binding" group="instance_properties">An expression binding also begins with the variable resolution operator, but is followed by a set of curly braces which wrap the expression value.</assert> For example, the following markup binds the value of a text input's "text" property to the "text" property of a <span class="code">Label</span> instance:</p>
 551 
 552 <pre class="code">
 553 &lt;TextField fx:id="textField"/&gt;
 554 &lt;Label text="${textField.text}"/&gt;
 555 </pre>
 556 
 557 <p>As the user types in the text input, the label's text content will be automatically updated.</p>
 558 
 559 <p>More complex expression are also supported. A list of supported constants and operators follows:</p>
 560 
 561 <table>
 562  <tr><td>"string"<br />'string'</td><td>A string constant</td></tr>
 563  <tr><td>true<br />false</td><td>A boolean constant</td></tr>
 564  <tr><td>null</td><td>A constant representing the null value</td></tr>
 565  <tr><td>50.0<br />3e5<br />42</td><td>A numerical constant</td></tr>
 566  <tr><td>- <br/>(unary operator)</td><td>Unary minus operator, applied on a number</td>
 567  <tr><td>! <br/>(unary operator)</td><td>Unary negation of a boolean</td></tr>
 568  <tr><td>+ - <br />
 569                         * /
 570                         %</td> <td>Numerical binary operators</td></tr>
 571  <tr><td>&& ||</td><td>Boolean binary operators</td></tr>
 572  <tr><td>&gt; &gt;= <br />
 573                    &lt; &lt;= <br />
 574                    == !=</td>
 575                    <td>Binary operators of comparison.<br/> Both arguments must be of type Comparable</td></tr>
 576 </table>
 577 
 578 <h3><a name="static_property_attributes">Static Properties</a></h3>
 579 <p><assert id="static_property_attributes" group="attributes">Attributes representing static properties are handled similarly to static property elements and use a similar syntax.</assert> For example, the earlier <span class="code">GridPane</span> markup shown earlier to demonstrate static property elements could be rewritten as follows:</p>
 580 
 581 <pre class="code">
 582 &lt;GridPane&gt;
 583     &lt;children&gt;
 584         &lt;Label text="My Label" GridPane.rowIndex="0" GridPane.columnIndex="0"/&gt;
 585     &lt;/children&gt;
 586 &lt;/TabPane&gt;
 587 </pre>
 588 
 589 <p><assert id="static_property_attributes_use" group="attributes">In addition to being more concise, static property attributes, like instance property attributes, support location, resource, and variable resolution operators, the only limitation being that it is not possible to create an expression binding to a static property.</assert></p>
 590 
 591 <h3><a name="event_handler_attributes">Event Handlers</a></h3>
 592 <p>Event handler attributes are a convenient means of attaching behaviors to document elements. Any class that defines a <span class="code">setOn<span class="variable">Event</span>()</span> method can be assigned an event handler in markup.</p>
 593 
 594 <p>FXML supports three types of event handler attributes: script event handlers, controller method event handlers and expressions. Each are discussed below.</p>
 595 
 596 <h4><a name="script_event_handlers">Script Event Handlers</a></h4>
 597 <p><assert id="script_event_handlers" group="event_handlers">A script event handler is an event handler that executes script code when the event is fired, similar to event handlers in HTML.</assert> For example, the following script-based handler for the button's "onAction" event uses JavaScript to write the text "You clicked me!" to the console when the user presses the button:</p>
 598 
 599 <pre class="code">
 600 &lt;?language javascript?&gt;
 601 ...
 602 
 603 &lt;VBox&gt;
 604     &lt;children&gt;
 605         &lt;Button text="Click Me!"
 606             onAction="java.lang.System.out.println('You clicked me!');"/&gt;
 607     &lt;/children&gt;
 608 &lt;/VBox&gt;
 609 </pre>
 610 
 611 <p><assert id="language_processing_instruction" group="event_handlers">Note the use of the language processing instruction at the beginning of the code snippet. This PI tells the FXML loader which scripting language should be used to execute the event handler. A page language must be specified whenever inline script is used in an FXML document, and can only be specified once per document. However, this does not apply to external scripts, which may be implemented using any number of supported scripting languages.</assert> Scripting is discussed in more detail in the next section.</p>
 612 
 613 <h4><a name="controller_method_event_handlers">Controller Method Event Handlers</a></h4>
 614 <p>A controller method event handler is a method defined by a document's "controller". A controller is an object that is associated with the deserialized contents of an FXML document and is responsible for coordinating the behaviors of the objects (often user interface elements) defined by the document.</p>
 615 
 616 <p><assert id="controller_method_event_handler_specification" group="event_handlers">A controller method event handler is specified by a leading hash symbol followed by the name of the handler method.</assert> For example:</p>
 617 
 618 <pre class="code">
 619 &lt;VBox fx:controller="com.foo.MyController"
 620     xmlns:fx="http://javafx.com/fxml"&gt;
 621     &lt;children&gt;
 622         &lt;Button text="Click Me!" onAction="#handleButtonAction"/&gt;
 623     &lt;/children&gt;
 624 &lt;/VBox&gt;
 625 </pre>
 626 
 627 <p><assert id="controller_attribute" group="event_handlers">Note the use of the <span class="code">fx:controller</span> attribute on the root element. This attribute is used to associate a controller class with the document.</assert> If <span class="code">MyController</span> is defined as follows:</p>
 628 
 629 <pre class="code">
 630 package com.foo;
 631 
 632 public class MyController {
 633     public void handleButtonAction(ActionEvent event) {
 634         System.out.println("You clicked me!");
 635     }
 636 }
 637 </pre>
 638 
 639 <p>the <span class="code">handleButtonAction()</span> will be called when the user presses the button, and the text "You clicked me!" will be written to the console.</p>
 640 
 641 <p><assert id="handler_method_signature" group="event_handlers">In general, a handler method should conform to the signature of a standard event handler; that is, it should take a single argument of a type that extends <span class="code">javafx.event.Event</span> and should return void (similar to an event delegate in C#). The event argument often carries important and useful information about the nature of the event;</assert> <assert id="handler_method_opt_arg" group="event_handlers">however, it is optional and may be omitted if desired</assert>.
 642 So this is also a valid handler:</p>
 643 
 644 <pre class="code">
 645 package com.foo;
 646 
 647 public class MyController {
 648     public void handleButtonAction() {
 649         System.out.println("You clicked me!");
 650     }
 651 }
 652 </pre>
 653 
 654 <p>Controllers are discussed in more detail in a later section.</p>
 655 
 656 <h4><a name="expression_handlers">Event handlers from expressions</a></h4>
 657 <p>Any expression that point to a <a href="#variable_resolution">variable</a> of javafx.event.EventHandler type
 658     can be used as an expression handler. </p>
 659 <p>
 660 Previous example using an expression handler:
 661 </p>


 667     &lt;/children&gt;
 668 &lt;/VBox&gt;
 669 </pre>
 670 
 671 <p> With the controller that contains a field like this </p>
 672     
 673 <pre class="code">
 674 public class MyController {
 675     
 676     @FXML
 677     public EventHandler<ActionEvent> onActionHandler = new EventHandler<>() { ... }
 678 
 679     ...
 680 }  
 681 </pre>
 682 
 683 <p> Note that other kinds of expressions, like <a href="#expression_binding">binding expressions</a>
 684     are not supported in this context. </p>
 685 
 686 <h4><a name="collections_and_property_handlers">Special handlers for collections and properties</a></h4>
 687 <p> Collections and object properties cannot be listen to using <span class="code">setOn<span class="variable">Event</span>()</span> methods.
 688     For these reason, special handler methods need to be used.
 689 <span class="code">ObservableList</span>, <span class="code">ObservableMap</span> or <span class="code">ObservableSet</span>
 690  uses a special <span class="code">onChange</span> attribute that points to a handler method with a <span class="code">ListChangeListner.Change</span>, <span class="code">MapChangeListener.Change</span> or <span class="code">SetChangeListener.Change</span> parameter respectively.
 691 </p>
 692 <pre class="code">
 693 &lt;VBox fx:controller="com.foo.MyController"
 694     xmlns:fx="http://javafx.com/fxml"&gt;
 695     &lt;children onChange="#handleChildrenChange"/&gt;
 696 &lt;/VBox&gt;
 697 </pre>
 698 
 699 where the handler method looks like this:
 700 
 701 <pre class="code">
 702 package com.foo;
 703 
 704 import javafx.collections.ListChangeListener.Change;
 705 
 706 public class MyController {
 707     public void handleChildrenChange(ListChangeListener.Change c) {
 708         System.out.println("Children changed!");
 709     }
 710 }
 711 </pre>
 712 
 713 <p>Similarly, the property handlers are methods that have the same parameters as changed method of ChangeListener :</p>
 714 <p><span class="code">changed(ObservableValue&lt;? extends T&gt; observable, T oldValue, T newValue)</span></p>
 715 
 716 <p>A handler for parent property would look like this</p>
 717 <pre class="code">
 718 public class MyController {
 719     public void handleParentChange(ObservableValue value, Parent oldValue, Parent newValue) {
 720         System.out.println("Parent changed!");
 721     }
 722 }
 723 </pre>
 724 
 725 <p>For convenience, the first parameter can be a subclass of <span class="code">ObservableValue</span>,
 726     e.g. <span class="code">Property</span></p>
 727 
 728 <p>For registering to a property, a special <span class="code">on&lt;propertyName&gt;Change</span>
 729 attribute must be used.</p>
 730 
 731 <pre class="code">
 732 &lt;VBox fx:controller="com.foo.MyController"
 733     xmlns:fx="http://javafx.com/fxml" onParentChange="#handleParentChange"/&gt;
 734 </pre>
 735     
 736 <p>Note that collections and properties do not currently support scripting handlers.</p>
 737 
 738 <h2><a name="scripting">Scripting</a></h2>
 739 <assert id="script_tag" group="scripting">The <span class="code">&lt;fx:script&gt;</span> tag allows a caller to import scripting code into or embed script within a FXML file. Any JVM scripting language can be used, including JavaScript, Groovy, and Clojure, among others. Script code is often used to define event handlers directly in markup or in an associated source file, since event handlers can often be written more concisely in more loosely-typed scripting languages than they can in a statically-typed language such as Java.</assert></p>
 740 
 741 <p>For example, the following markup defines a function called <span class="code">handleButtonAction()</span> that is called by the action handler attached to the <span class="code">Button</span> element:</p>
 742 
 743 <pre class="code">
 744 &lt;?language javascript?&gt;
 745 
 746 &lt;?import javafx.scene.control.*?&gt;
 747 &lt;?import javafx.scene.layout.*?&gt;
 748 
 749 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 750     &lt;fx:script&gt;
 751 
 752     function handleButtonAction(event) {
 753        java.lang.System.out.println('You clicked me!');
 754     }
 755     &lt;/fx:script&gt;
 756 
 757     &lt;children&gt;
 758         &lt;Button text="Click Me!" onAction="handleButtonAction(event);"/&gt;
 759     &lt;/children&gt;
 760 &lt;/VBox&gt;
 761 </pre>


 772 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 773     &lt;fx:script source="example.js" charset="cp1252"/&gt;
 774 
 775     &lt;children&gt;
 776         &lt;Button text="Click Me!" onAction="handleButtonAction(event);"/&gt;
 777     &lt;/children&gt;
 778 &lt;/VBox&gt;
 779 </pre>
 780 
 781 <div class="caption">example.js</div>
 782 <pre class="code">
 783 
 784 function handleButtonAction(event) {
 785    java.lang.System.out.println('You clicked me!');
 786 }
 787 </pre>
 788 
 789 <p>It is often preferable to separate code from markup in this way, since many text editors support syntax highlighting for the various scripting languages supported by the JVM. It can also help improve readability of the source code and markup.</p>
 790 
 791 <assert id="script_blocks_not_limited" group="scripting">
 792 <p>Note that script blocks are not limited to defining event handler functions. Script code is executed as it is processed, so it can also be used to dynamically configure the structure of the resulting output. As a simple example, the following FXML includes a script block that defines a variable named "labelText". The value of this variable is used to populate the text property of a <span class="code">Label</span> instance:</p>
 793 
 794 <pre class="code">
 795 &lt;fx:script&gt;
 796 var myText = "This is the text of my label.";
 797 &lt;/fx:script&gt;
 798 
 799 ...
 800 
 801 &lt;Label text="$myText"/&gt;
 802 </pre>
 803 </assert>
 804 
 805 <p><strong>Warning:</strong>As of JavaFX 8, <span class="code">importClass()</span> javascript function is no longer supported. You have to use fully qualified names as in the example above or load a nashorn compatibility script.</p>
 806 
 807 <pre class="code">
 808 load("nashorn:mozilla_compat.js");
 809 importClass(java.lang.System);
 810 
 811 function handleButtonAction(event) {
 812    System.out.println('You clicked me!');
 813 }
 814 </pre> 
 815 
 816 <h2><a name="controllers">Controllers</a></h2>
 817 <p>While it can be convenient to write simple event handlers in script, either inline or defined in external files, it is often preferable to define more complex application logic in a compiled, strongly-typed language such as Java. As discussed earlier, the <span class="code">fx:controller</span> attribute allows a caller to associate a "controller" class with an FXML document. A controller is a compiled class that implements the "code behind" the object hierarchy defined by the document.</p>
 818 
 819 <p>As shown earlier, controllers are often used to implement event handlers for user interface elements defined in markup:</p>
 820 
 821 <pre class="code">
 822 &lt;VBox fx:controller="com.foo.MyController"
 823     xmlns:fx="http://javafx.com/fxml"&gt;
 824     &lt;children&gt;
 825         &lt;Button text="Click Me!" onAction="#handleButtonAction"/&gt;
 826     &lt;/children&gt;
 827 &lt;/VBox&gt;
 828 </pre>
 829 
 830 <pre class="code">
 831 package com.foo;
 832 
 833 public class MyController {
 834     public void handleButtonAction(ActionEvent event) {
 835         System.out.println("You clicked me!");
 836     }
 837 }
 838 </pre>
 839 
 840 <p><assert id="handlers_initialize" group="controllers">In many cases, it is sufficient to simply declare event handlers in this manner. However, when more control over the behavior of the controller and the elements it manages is required, the controller can define an <span class="code">initialize()</span> method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded</assert>:</p>
 841 
 842 <pre class="code">
 843 public void initialize();
 844 </pre>
 845 
 846 <p><assert id="post-processing" group="controllers">This allows the implementing class to perform any necessary post-processing on the content.</assert> It also provides the controller with access to the resources that were used to load the document and the location that was used to resolve relative paths within the document (commonly equivalent to the location of the document itself).</p>
 847 
 848 <p>For example, the following code defines an <span class="code">initialize()</span> method that attaches an action handler to a button in code rather than via an event handler attribute, as was done in the previous example. The button instance variable is injected by the loader as the document is read. The resulting application behavior is identical:</p>
 849 
 850 <pre class="code">
 851 &lt;VBox fx:controller="com.foo.MyController"
 852     xmlns:fx="http://javafx.com/fxml"&gt;
 853     &lt;children&gt;
 854         &lt;Button fx:id="button" text="Click Me!"/&gt;
 855     &lt;/children&gt;
 856 &lt;/VBox&gt;
 857 </pre>
 858 
 859 <pre class="code">
 860 package com.foo;
 861 
 862 public class MyController implements Initializable {
 863     public Button button;
 864 
 865     @Override
 866     public void initialize(URL location, Resources resources)
 867         button.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
 868             @Override
 869             public void handle(ActionEvent event) {
 870                 System.out.println("You clicked me!");
 871             }
 872         });
 873     }
 874 }
 875 </pre>
 876 
 877 <h3><a name="fxml_annotation">@FXML</a></h3>
 878 <p><assert id="public_controller_access" group="controllers">Note that, in the previous examples, the controller member fields and event handler methods were declared as public so they can be set or invoked by the loader.</assert> In practice, this is not often an issue, since a controller is generally only visible to the FXML loader that creates it. <assert id="FXML_controller_access" group="controllers">However, for developers who prefer more restricted visibility for controller fields or handler methods, the <span class="code">javafx.fxml.FXML</span> annotation can be used. This annotation marks a protected or private class member as accessible to FXML.</assert></span>














 879 
 880 <p>For example, the controllers from the previous examples could be rewritten as follows:</p>
 881 
 882 <pre class="code">
 883 package com.foo;
 884 
 885 public class MyController {
 886     @FXML
 887     private void handleButtonAction(ActionEvent event) {
 888         System.out.println("You clicked me!");
 889     }
 890 }
 891 </pre>
 892 
 893 <pre class="code">
 894 package com.foo;
 895 
 896 public class MyController implements Initializable {
 897     @FXML private Button button;
 898 
 899     @FXML
 900     protected void initialize()
 901         button.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
 902             @Override
 903             public void handle(ActionEvent event) {
 904                 System.out.println("You clicked me!");
 905             }
 906         });
 907     }
 908 }
 909 </pre>
 910 
 911 <p>In the first version, the <span class="code">handleButtonAction()</span> is tagged with <span class="code">@FXML</span> to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The <span class="code">initialize()</span> method is similarly annotated.</p>
 912 
 913 <p><assert id="trusted_code_only" group="controllers">Note that the <span class="code">@FXML</span> annotation can currently only be used with trusted code.</assert> Because the FXML loader relies on reflection to set member fields and invoke member methods, it must call <span class="code">setAccessible()</span> on any non-public <span class="code">Field</span>. <span class="code">setAccessible()</span> is a privileged operation that can only be executed in a secure context. This may change in a future release.</p>
 914 
 915 <h3><a name="nested_controllers">Nested Controllers</a></h3>
 916 <p><assert id="nested_fxml_mapping" group="controllers">Controller instances for nested FXML documents loaded via the <span class="code">&lt;fx:include&gt;</span> element are mapped directly to member fields of the including controller.</assert> This allows a developer to easily access functionality defined by an include (such as a dialog window presented by an application's main window controller). For example, given the following code:
 917 
 918 <div class="caption">main_window_content.fxml</div>
 919 <pre class="code">
 920 &lt;VBox fx:controller="com.foo.MainController"&gt;
 921    &lt;fx:define&gt;
 922       &lt;fx:include fx:id="dialog" source="dialog.fxml"/&gt;
 923    &lt;/fx:define&gt;
 924    ...
 925 &lt;/VBox&gt;
 926 </pre>
 927 
 928 <div class="caption">MainController.java</div>
 929 <pre class="code">
 930 public class MainController extends Controller {
 931     @FXML private Window dialog;
 932     @FXML private DialogController dialogController;
 933 
 934     ...
 935 }
 936 </pre>
 937 
 938 <p>when the controller's <span class="code">initialize()</span> method is called, the <span class="code">dialog</span> field will contain the root element loaded from the "dialog.fxml" include, and the <span class="code">dialogController</span> field will contain the include's controller. The main controller can then invoke methods on the included controller, to populate and show the dialog, for example. Note that as the content of the file referenced by fx:include otherwise would become part of the scene graph spanned from main_window_content.fxml, it is necessary to wrap fx:include by fx:define to separate the scene graphs of both windows.</p>
 939 
 940 <h2><a name="fxmlloader">FXMLLoader</a></h2>
 941 <p>The <span class="code">FXMLLoader</span> class is responsible for actually loading an FXML source file and returning the resulting object graph. For example, the following code loads an FXML file from a location on the classpath relative to the loading class and localizes it with a resource bundle named "com.foo.example". The type of the root element is assumed to be a subclass of <span class="code">javafx.scene.layout.Pane</span>, and the document is assumed to define a controller of type <span class="code">MyController</span>:</p>
 942 
 943 <pre class="code">
 944 URL location = getClass().getResource("example.fxml");
 945 ResourceBundle resources = ResourceBundle.getBundle("com.foo.example");
 946 FXMLLoader fxmlLoader = new FXMLLoader(location, resources);
 947 
 948 Pane root = (Pane)fxmlLoader.load();
 949 MyController controller = (MyController)fxmlLoader.getController();
 950 </pre>
 951 
 952 <p><assert id="loader_instance_hierarchy" group="fxml_loader">Note that the output of an <span class="code">FXMLLoader#load()</span> operation is an instance hierarchy that reflects the actual named classes in the document, not <span class="code">org.w3c.dom</span> nodes representing those classes.</assert> Internally, <span class="code">FXMLLoader</span> uses the <span class="code">javax.xml.stream</span> API (also known as the <i>Streaming API for XML</i>, or <i>StAX</i>) to load an FXML document. StAX is an extremely efficient event-based XML parsing API that is conceptually similar to its W3C predecessor, SAX. It allows an FXML document to be processed in a single pass, rather than loaded into an intermediate DOM structure and then post-processed.</p>
 953 
 954 <h3><a name="custom_components">Custom Components</a></h3>
 955 <p>The <assert id="loader_setRoot" group="fxml_loader"><span class="code">setRoot()</span></assert> and <assert id="loader_setController" group="fxml_loader"><span class="code">setController()</span></assert> methods of <span class="code">FXMLLoader</span> allow a caller to inject document root and controller values, respectively, into the document namespace, rather than delegating creation of these values to <span class="code">FXMLLoader</span> itself. This allows a developer to easily create reusable controls that are internally implemented using markup, but (from an API perspective) appear identically to controls implemented programmatically.</p>
 956 
 957 <p>For example, the following markup defines the structure of a simple custom control containing a <span class="code">TextField</span> and a <span class="code">Button</span> instance. The root container is defined as an instance of <span class="code">javafx.scene.layout.VBox</span>:</p>
 958 
 959 <pre class="code">
 960 &lt;?import javafx.scene.*?&gt;
 961 &lt;?import javafx.scene.control.*?&gt;
 962 &lt;?import javafx.scene.layout.*?&gt;
 963 
 964 &lt;fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml"&gt;
 965     &lt;TextField fx:id="textField"/&gt;
 966     &lt;Button text="Click Me" onAction="#doSomething"/&gt;
 967 &lt;/fx:root&gt;
 968 </pre>
 969 
 970 <p>As mentioned earlier, the <span class="code">&lt;fx:root&gt;</span> tag creates a reference to a previously defined root element. The value of this element is obtained by calling the <span class="code">getRoot()</span> method of <span class="code">FXMLLoader</span>. <assert id="loader_setRoot_sequence" group="fxml_loader">Prior to calling <span class="code">load()</span>, the caller must specify this value via a call to <span class="code">setRoot()</span></assert>. <assert id="loader_setController_sequence" group="fxml_loader">The caller may similarly provide a value for the document's controller by calling <span class="code">setController()</span>, which sets the value that will be used as the document's controller when the document is read</assert>. These two methods are commonly used together when creating custom FXML-based components.</p>
 971 
 972 <p>In the following example, the <span class="code">CustomControl</span> class extends <span class="code">VBox</span> (the type declared by the <span class="code">&lt;fx:root&gt;</span> element), and sets itself as both the root and controller of the FXML document in its constructor. When the document is loaded, the contents of <span class="code">CustomControl</span> will be populated with the contents of the previous FXML document:</p>
 973 
 974 <pre class="code">
 975 package fxml;
 976 
 977 import java.io.IOException;
 978 
 979 import javafx.beans.property.StringProperty;
 980 import javafx.fxml.FXML;
 981 import javafx.fxml.FXMLLoader;
 982 import javafx.scene.control.TextField;
 983 import javafx.scene.layout.VBox;
 984 
 985 public class CustomControl extends VBox {
 986     @FXML private TextField textField;
 987 
 988     public CustomControl() {
 989         FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("custom_control.fxml"));
 990         fxmlLoader.setRoot(this);
 991         fxmlLoader.setController(this);
 992 


   1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2 
   3 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">    
   4 <head>
   5 <link href="fxml.css" rel="stylesheet"/>    
   6 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
   7 <title>Introduction to FXML | JavaFX 9</title>
   8 <meta name="description" content="The document introduces FXML, an XML-based declarative markup language for defining user interfaces in JavaFX 9 applications."/>
   9 <meta name="keywords" content="JavaFX 9, FXML, JavaFX GUI development, web development, Java application development, GUI applications, rich internet applications, RIA, expressive content"/>
  10 </head>
  11 <body>
  12 
  13 <div class="fx-code-header">
  14 <div class="version"><br/>Release: JavaFX 9</div>
  15 </div>
  16 
  17 <h1>Introduction to FXML</h1>
  18 <p class="subtitle">Last updated: 3/3/2017</p>
  19 
  20 <h2>Contents</h2>
  21 <ul class="contents">
  22 <li><a href="#overview">Overview</a></li>
  23 <li>
  24     <a href="#elements">Elements</a>
  25     <ul>
  26     <li>
  27         <a href="#class_instance_elements">Class Instance Elements</a>
  28         <ul>
  29         <li><a href="#instance_declaration_elements">Instance Declarations</a></li>
  30         <li><a href="#include_elements">&lt;fx:include&gt;</a></li>
  31         <li><a href="#constant_elements">&lt;fx:constant&gt;</a></li>
  32         <li><a href="#reference_elements">&lt;fx:reference&gt;</a></li>
  33         <li><a href="#copy_elements">&lt;fx:copy&gt;</a></li>
  34         <li><a href="#root_elements">&lt;fx:root&gt;</a></li>
  35         </ul>
  36     </li>
  37 
  38     <li>


  97 <p>This document introduces the FXML markup language and explains how it can be used to simplify development of JavaFX applications.</p>
  98 
  99 <h2><a name="elements">Elements</a></h2>
 100 <p>In FXML, an XML element represents one of the following:</p>
 101 <ul>
 102 <li>A class instance</li>
 103 <li>A property of a class instance</li>
 104 <li>A "static" property</li>
 105 <li>A "define" block</li>
 106 <li>A block of script code</li>
 107 </ul>
 108 
 109 <p>Class instances, instance properties, static properties, and define blocks are discussed in this section below. Scripting is discussed in a later section.</p>
 110 
 111 <h3><a name="class_instance_elements">Class Instance Elements</a></h3>
 112 <p>Class instances can be constructed in FXML in several ways. The most common is via instance declaration elements, which simply create a new instance of a class by name. Other ways of creating class instances include referencing existing values, copying existing values, and including external FXML files. Each is discussed in more detail below.</p>
 113 
 114 <h4><a name="instance_declaration_elements">Instance Declarations</a></h4>
 115 <p><assert id="instance_declaration" group="instance_declarations">If an element's tag is considered an instance declaration if the tag begins with uppercase letter (and the class is imported)</assert> or, as in Java, <assert id="fully_qualified_name" group="instance_declarations">it denotes a fully-qualified (including the package name) name of a class.</assert> When the FXML loader (also introduced later) encounters such an element, it creates an instance of that class.</p>
 116 
 117 <p><assert id="import" group="instance_declarations">Importing a class is done using the "import" processing instruction (PI). For example, the following PI imports the <span class="code">javafx.scene.control.Label</span> class into the current FXML document’s namespace:</p>
 118 
 119 <pre class="code">
 120 &lt;?import javafx.scene.control.Label?&gt;
 121 </pre>
 122 
 123 <p>This PI imports all classes from the javafx.scene.control package into the current namespace:</p>
 124 
 125 <pre class="code">
 126 &lt;?import javafx.scene.control.*?&gt;
 127 </pre>
 128 </assert>
 129 
 130 <p><assert id="instantiation_java_bean" group="instance_declarations">Any class that adheres to JavaBean constructor and property naming conventions can be readily instantiated and configured using FXML.</assert> The following is a simple but complete example that creates an instance of <span class="code">javafx.scene.control.Label</span> and sets its "text" property to "Hello, World!":</p>
 131 
 132 <pre class="code">
 133 &lt;?import javafx.scene.control.Label?&gt;
 134 &lt;Label text="Hello, World!"/&gt;
 135 </pre>
 136 
 137 <p>Note that the <span class="code">Label</span>’s "text" property in this example is set using an XML attribute. Properties can also be set using nested property elements. Property elements are discussed in more detail later in this section. Property attributes are discussed in a later section.</p>
 138 
 139 <p>Classes that don't conform to Bean conventions can also be constructed in FXML, using an object called a "builder". Builders are discussed in more detail later.</p>
 140 
 141 <h5>Maps</h5>
 142 <p>Internally, the FXML loader uses an instance of <span class="code">com.sun.javafx.fxml.BeanAdapter</span> to wrap an instantiated object and invoke its setter methods. This (currently) private class implements the <span class="code">java.util.Map</span> interface and allows a caller to get and set Bean property values as key/value pairs.</p>
 143 
 144 <p><assert id="map_instantiaton" group="instance_declarations">If an element represents a type that already implements <span class="code">Map</span> (such as <span class="code">java.util.HashMap</span>), it is not wrapped and its <span class="code">get()</span> and <span class="code">put()</span> methods are invoked directly.</assert> For example, the following FXML creates an instance of <span class="code">HashMap</span> and sets its "foo" and "bar" values to "123" and "456", respectively:
 145 
 146 <pre class="code">
 147 &lt;HashMap foo="123" bar="456"/&gt;
 148 </pre>
 149 
 150 <h5>fx:value</h5>
 151 <p><assert id="instantiation_no_default_constructor" group="instance_declarations">The <span class="code">fx:value</span> attribute can be used to initialize an instance of a type that does not have a default constructor but provides a static <span class="code">valueOf(String)</span> method.</assert> For example, <span class="code">java.lang.String</span> as well as each of the primitive wrapper types define a <span class="code">valueOf()</span> method and can be constructed in FXML as follows:</p>
 152 
 153 <pre class="code">
 154 &lt;String fx:value="Hello, World!"/&gt;
 155 &lt;Double fx:value="1.0"/&gt;
 156 &lt;Boolean fx:value="false"/&gt;
 157 </pre>
 158 
 159 <p>Custom classes that define a static <span class="code">valueOf(String)</span> method can also be constructed this way.</p>
 160 
 161 <h5>fx:factory</h5>
 162 <p><assert id="instantiation_factory" group="instance_declarations">The <span class="code">fx:factory</span> attribute is another means of creating objects whose classes do not have a default constructor. The value of the attribute is the name of a static, no-arg factory method for producing class instances.</assert> For example, the following markup creates an instance of an observable array list, populated with three string values:</p>
 163 
 164 <pre class="code">
 165 &lt;FXCollections fx:factory="observableArrayList"&gt;
 166     &lt;String fx:value="A"/&gt;
 167     &lt;String fx:value="B"/&gt;
 168     &lt;String fx:value="C"/&gt;
 169 &lt;/FXCollections&gt;
 170 </pre>
 171 
 172 <h5>Builders</h5>
 173 <p><assert id="instantiation_builder" group="instance_declarations">A third means of creating instances of classes that do not conform to Bean conventions (such as those representing immutable values) is a "builder".</assert> The builder design pattern delegates object construction to a mutable helper class (called a "builder") that is responsible for manufacturing instances of the immutable type.</p>
 174 
 175 <p>Builder support in FXML is provided by two interfaces. The <span class="code">javafx.util.Builder</span> interface defines a single method named <span class="code">build()</span> which is responsible for constructing the actual object:</p>
 176 
 177 <pre class="code">
 178 public interface Builder&lt;T&gt; {
 179     public T build();
 180 }
 181 </pre>
 182 
 183 <p>A <span class="code">javafx.util.BuilderFactory</span> is responsible for producing builders that are capable of instantiating a given type:</p>
 184 
 185 <pre class="code">
 186 public interface BuilderFactory {
 187     public Builder&lt;?&gt; getBuilder(Class&lt;?&gt; type);
 188 }
 189 </pre>
 190 
 191 <p>A default builder factory, <span class="code">JavaFXBuilderFactory</span>, is provided in the <span class="code">javafx.fxml</span> package. This factory is capable of creating and configuring most immutable JavaFX types. For example, the following markup uses the default builder to create an instance of the immutable <span class="code">javafx.scene.paint.Color</span> class:
 192 
 193 <pre class="code">
 194 &lt;Color red="1.0" green="0.0" blue="0.0"/&gt;
 195 </pre>
 196 
 197 <p>Note that, unlike Bean types, which are constructed when the element's start tag is processed, objects constructed by a builder are not instantiated until the element's closing tag is reached. This is because all of the required arguments may not be available until the element has been fully processed. For example, the Color object in the preceding example could also be written as:</p>
 198 
 199 <pre class="code">
 200 &lt;Color&gt;
 201     &lt;red&gt;1.0&lt;/red&gt;
 202     &lt;green&gt;0.0&lt;/green&gt;
 203     &lt;blue&gt;0.0&lt;/blue&gt;
 204 &lt;/Color&gt;
 205 </pre>
 206 
 207 <p>The <span class="code">Color</span> instance cannot be fully constructed until all three of the color components are known.</p>
 208 
 209 <p>When processing markup for an object that will be constructed by a builder, the <span class="code">Builder</span> instances are treated like value objects - if a <span class="code">Builder</span> implements the <span class="code">Map</span> interface, the <span class="code">put()</span> method is used to set the builder's attribute values. Otherwise, the builder is wrapped in a <span class="code">BeanAdapter</span> and its properties are assumed to be exposed via standard Bean setters.</p>
 210 
 211 <h4><a name="include_elements">&lt;fx:include&gt;</a></h4>
 212 <p>The <span class="code">&lt;fx:include&gt;</span> tag creates an object from FXML markup defined in another file. It is used as follows:</p>
 213 
 214 <pre class="code">
 215 &lt;fx:include source="<span class="variable">filename</span>"/&gt;
 216 </pre>
 217 
 218 <p>where <span class="variable">filename</span> is the name of the FXML file to include. <assert id="include_leading_slash_character" group="instance_declarations">Values that begin with a leading slash character are treated as relative to the classpath.</assert> <assert id="include_no_leading_slash_character" group="instance_declarations">Values with no leading slash are considered relative to the path of the current document.</assert></p>
 219 
 220 <p>For example, given the following markup:</p>
 221 
 222 <pre class="code">
 223 &lt;?import javafx.scene.control.*?&gt;
 224 &lt;?import javafx.scene.layout.*?&gt;
 225 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 226     &lt;children&gt;
 227         &lt;fx:include source="my_button.fxml"/&gt;
 228     &lt;/children&gt;
 229 &lt;/VBox&gt;
 230 </pre>
 231 
 232 <p>If <span class="filename">my_button.fxml</span> contains the following:
 233 
 234 <pre class="code">
 235 &lt;?import javafx.scene.control.*?&gt;
 236 &lt;Button text="My Button"/&gt;
 237 </pre>
 238 
 239 <p>the resulting scene graph would contain a <span class="code">VBox</span> as a root object with a single <span class="code">Button</span> as a child node.</p>
 240 
 241 <p>Note the use of the "fx" namespace prefix. This is a reserved prefix that defines a number of elements and attributes that are used for internal processing of an FXML source file. It is generally declared on the root element of a FXML document. Other features provided by the "fx" namespace are described in the following sections.</p>
 242 
 243 <p><span class="code">&lt;fx:include&gt;</span> also supports attributes for specifying the name of the resource bundle that should be used to localize the included content, as well as the character set used to encode the source file. Resource resolution is discussed in a later section.</p>
 244 
 245 <pre class="code">
 246 &lt;fx:include source="<span class="variable">filename</span>" resources="<span class="variable">resource_file</span>" charset="utf-8"/&gt;
 247 </pre>
 248 
 249 <h4><a name="constant_elements">&lt;fx:constant&gt;</a></h4>
 250 <p><assert id="constant" group="instance_declarations">The <span class="code">&lt;fx:constant&gt;</span> element creates a reference to a class constant.</assert> For example, the following markup sets the value of the "minWidth" property of a<span class="code">Button</span> instance to the value of the <span class="code">NEGATIVE_INFINITY</span> constant defined by the <span class="code">java.lang.Double</span> class:</p>
 251 
 252 <pre class="code">
 253 &lt;Button&gt;
 254     &lt;minHeight&gt;&lt;Double fx:constant="NEGATIVE_INFINITY"/&gt;&lt;/minHeight&gt;
 255 &lt;/Button&gt;
 256 </pre>
 257 
 258 <h4><a name="reference_elements">&lt;fx:reference&gt;</a></h4>
 259 <p><assert id="reference" group="instance_declarations">The <span class="code">&lt;fx:reference&gt;</span> element creates a new reference to an existing element.</assert> Wherever this tag appears, it will effectively be replaced by the value of the named element. It is used in conjunction with either the <span class="code">fx:id</span> attribute or with a script variables, both of which are discussed in more detail in later sections. The "source" attribute of the <span class="code">&lt;fx:reference&gt;</span> element specifies the name of the object to which the new element will refer.</p>
 260 
 261 <p>For example, the following markup assigns a previously-defined <span class="code">Image</span> instance named "myImage" to the "image" property of an <span class="code">ImageView</span> control:</p>
 262 
 263 <pre class="code">
 264 &lt;ImageView&gt;
 265     &lt;image&gt;
 266         &lt;fx:reference source="myImage"/&gt;
 267     &lt;/image&gt;
 268 &lt;/ImageView&gt;
 269 </pre>
 270 
 271 <p>Note that, since it is also possible to dereference a variable using the attribute variable resolution operator (discussed later in the <a href="#attributes">Attributes</a> section), <span class="code">fx:reference</span> is generally only used when a reference value must be specified as an element, such as when adding the reference to a collection:</p>
 272 
 273 <pre class="code">
 274 &lt;ArrayList&gt;
 275     &lt;fx:reference source="element1"/&gt;
 276     &lt;fx:reference source="element2"/&gt;
 277     &lt;fx:reference source="element3"/&gt;
 278 &lt;/ArrayList&gt;
 279 </pre>
 280 
 281 <p>For most other cases, using an attribute is simpler and more concise.</p>
 282 
 283 <h4><a name="copy_elements">&lt;fx:copy&gt;</a></h4>
 284 <p><assert id="copy" group="instance_declarations">The <span class="code">&lt;fx:copy&gt;</span> element creates a copy of an existing element.</assert> Like <span class="code">&lt;fx:reference&gt;</span>, it is used with the fx:id attribute or a script variable. The element's "source" attribute specifies the name of the object that will be copied. The source type must define a copy constructor that will be used to construct the copy from the source value.</p>
 285 
 286 <p>At the moment, no JavaFX platform classes provide such a copy constructor, so this element is provided primarily for use by application developers. This may change in a future release.</p>
 287 
 288 <h4><a name="root_elements">&lt;fx:root&gt;</a></h4>
 289 <p><assert id="root" group="instance_declarations">The <span class="code">&lt;fx:root&gt;</span> element creates a reference to a previously defined root element. It is only valid as the root node of an FXML document.</assert> <span class="code">&lt;fx:root&gt;</span> is used primarily when creating custom controls that are backed by FXML markup. This is discussed in more detail in the <a href="#fxmlloader">FXMLLoader</a> section.</p>
 290 
 291 <h3><a name="property_elements">Property Elements</a></h3>
 292 <p>Elements whose tag names begin with a lowercase letter represent object properties. A property element may represent one of the following:</p>
 293 
 294 <ul>
 295 <li>A property setter</li>
 296 <li>A read-only list property</li>
 297 <li>A read-only map property</li>
 298 </ul>
 299 
 300 <h4><a name="property_setter_elements">Property Setters</a></h4>
 301 <p><assert id="property_setter" group="property_elements">If an element represents a property setter, the contents of the element (which must be either a text node or a nested class instance element) are passed as the value to the setter for the property.</assert></p>
 302 
 303 <p>For example, the following FXML creates an instance of the <span class="code">Label</span> class and sets the value of the label's "text" property to "Hello, World!":</p>
 304 
 305 <pre class="code">
 306 &lt;?import javafx.scene.control.Label?&gt;
 307 &lt;Label&gt;
 308     &lt;text&gt;Hello, World!&lt;/text&gt;
 309 &lt;/Label&gt;
 310 </pre>
 311 
 312 <p>This produces the same result as the earlier example which used an attribute to set the "text" property:</p>
 313 
 314 <pre class="code">
 315 &lt;?import javafx.scene.control.Label?&gt;
 316 &lt;Label text="Hello, World!"/&gt;
 317 </pre>
 318 
 319 <p>Property elements are generally used when the property value is a complex type that can't be represented using a simple string-based attribute value, or when the character length of the value is so long that specifying it as an attribute would have a negative impact on readability.</p>
 320 
 321 <h5>Type Coercion</h5>
 322 <p><assert id="coercion" group="property_elements">FXML uses "type coercion" to convert property values to the appropriate type as needed.</assert> Type coercion is required because the only data types supported by XML are elements, text, and attributes (whose values are also text). However, Java supports a number of different data types including built-in primitive value types as well as extensible reference types.</p>
 323 
 324 <p>The FXML loader uses the <span class="code">coerce()</span> method of <span class="code">BeanAdapter</span> to perform any required type conversions. This method is capable of performing basic primitive type conversions such as <span class="code">String</span> to <span class="code">boolean</span> or <span class="code">int</span> to <span class="code">double</span>, and will also convert <span class="code">String</span> to <span class="code">Class</span> or <span class="code">String</span> to <span class="code">Enum</span>. Additional conversions can be implemented by defining a static <span class="code">valueOf()</span> method on the target type.</p>
 325 
 326 <h4><a name="read_only_list_property_elements">Read-Only List Properties</a></h4>
 327 <p><assert id="read_only_list_property" group="property_elements">A read-only list property is a Bean property whose getter returns an instance of <span class="code">java.util.List</span> and has no corresponding setter method. The contents of a read-only list element are automatically added to the list as they are processed.</assert></p>
 328 
 329 <p>For example, the "children" property of <span class="code">javafx.scene.Group</span> is a read-only list property representing the group's child nodes:</p>
 330 
 331 <pre class="code">
 332 &lt;?import javafx.scene.*?&gt;
 333 &lt;?import javafx.scene.shape.*?&gt;
 334 &lt;Group xmlns:fx="http://javafx.com/fxml"&gt;
 335     &lt;children&gt;
 336         &lt;Rectangle fx:id="rectangle" x="10" y="10" width="320" height="240"
 337             fill="#ff0000"/&gt;
 338         ...
 339     &lt;/children&gt;
 340 &lt;/Group&gt;
 341 </pre>
 342 
 343 <p>As each sub-element of the <span class="code">&lt;children&gt;</span> element is read, it is added to the list returned by <span class="code">Group#getChildren()</span>.
 344 
 345 <h4><a name="read_only_map_property_elements">Read-Only Map Properties</a></h4>
 346 <p><assert id="read_only_map_property" group="property_elements">A read-only map property is a bean property whose getter returns an instance of <span class="code">java.util.Map</span> and has no corresponding setter method. The attributes of a read-only map element are applied to the map when the closing tag is processed.</assert></p>
 347 
 348 <p>The "properties" property of <span class="code">javafx.scene.Node</span> is an example of a read-only map property. The following markup sets the "foo" and "bar" properties of a <span class="code">Label</span> instance to "123" and "456", respectively:</p>
 349 
 350 <pre class="code">
 351 &lt;?import javafx.scene.control.*?&gt;
 352 &lt;Button&gt;
 353     &lt;properties foo="123" bar="456"/&gt;
 354 &lt;/Button&gt;
 355 </pre>
 356 
 357 <p><assert id="read_only_property_type_treating" group="property_elements">Note that a read-only property whose type is neither a <span class="code">List</span> nor a <span class="code">Map</span> will be treated as if it were a read-only map. The return value of the getter method will be wrapped in a <span class="code">BeanAdapter</span> and can be used in the same way as any other read-only map.</assert></p>
 358 
 359 <h4><a name="default_properties">Default Properties</a></h4>
 360 <p><assert id="default_property" group="property_elements">A class may define a "default property" using the <span class="code">@DefaultProperty</span> annotation defined in the <span class="code">javafx.beans</span> package. If present, the sub-element representing the default property can be omitted from the markup.</assert></p>
 361 
 362 <p>For example, since <span class="code">javafx.scene.layout.Pane</span> (the superclass of <span class="code">javafx.scene.layout.VBox</span>) defines a default property of "children", a <span class="code">&lt;children&gt;</span> element is not required; the loader will automatically add the sub-elements of the <span class="code">VBox</span> to the container's "children" collection:</p>
 363 
 364 <pre class="code">
 365 &lt;?import javafx.scene.*?&gt;
 366 &lt;?import javafx.scene.shape.*?&gt;
 367 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 368     &lt;Button text="Click Me!"/&gt;
 369     ...
 370 &lt;/VBox&gt;
 371 </pre>
 372 
 373 <p>Note that default properties are not limited to collections. If an element's default property refers to a scalar value, any sub-element of that element will be set as the value of the property.</p>
 374 
 375 <p>For example, since <span class="code">javafx.scene.control.ScrollPane</span> defines a default property of "content", a scroll pane containing a <span class="code">TextArea</span> as its content can be specified as follows:
 376 
 377 <pre class="code">
 378 &lt;ScrollPane&gt;
 379     &lt;TextArea text="Once upon a time..."/&gt;
 380 &lt;/ScrollPane&gt;
 381 </pre>
 382 
 383 <p>Taking advantage of default properties can significantly reduce the verbosity of FXML markup.</p>
 384 
 385 <h3><a name="static_property_elements">Static Properties</a></h3>
 386 <p><assert id="static_property" group="elements">An element may also represent a "static" property (sometimes called an "attached property"). Static properties are properties that only make sense in a particular context. They are not intrinsic to the class to which they are applied, but are defined by another class (often, the parent container of a control).</assert></p>
 387 
 388 <p>Static properties are prefixed with the name of class that defines them. For example, The following FXML invokes the static setter for <span class="code">GridPane</span>'s "rowIndex" and "columnIndex" properties:</p>
 389 
 390 <pre class="code">
 391 &lt;GridPane&gt;
 392     &lt;children&gt;
 393         &lt;Label text="My Label"&gt;
 394             &lt;GridPane.rowIndex&gt;0&lt;/GridPane.rowIndex&gt;
 395        &lt;GridPane.columnIndex&gt;0&lt;/GridPane.columnIndex&gt;
 396         &lt;/Label&gt;
 397     &lt;/children&gt;
 398 &lt;/TabPane&gt;
 399 </pre>
 400 
 401 <p>This translates roughly to the following in Java:</p>
 402 
 403 <pre class="code">
 404 GridPane gridPane = new GridPane();
 405 
 406 Label label = new Label();
 407 label.setText("My Label");
 408 
 409 GridPane.setRowIndex(label, 0);
 410 GridPane.setColumnIndex(label, 0);
 411 
 412 gridPane.getChildren().add(label);
 413 </pre>
 414 
 415 The calls to <span class="code">GridPane#setRowIndex()</span> and <span class="code">GridPane#setColumnIndex()</span> "attach" the index data to the <span class="code">Label</span> instance. <span class="code">GridPane</span> then uses these during layout to arrange its children appropriately. Other containers, including <span class="code">AnchorPane</span>, <span class="code">BorderPane</span>, and <span class="code">StackPane</span>, define similar properties.</p>
 416 
 417 <p>As with instance properties, static property elements are generally used when the property value cannot be efficiently represented by an attribute value. Otherwise, static property attributes (discussed in a later section) will generally produce more concise and readable markup.</p>
 418 
 419 <h3><a name="define_elements">Define Blocks</a></h3>
 420 <p><assert id="define" group="elements">The <span class="code">&lt;fx:define&gt;</span> element is used to create objects that exist outside of the object hierarchy but may need to be referred to elsewhere.</assert></p>
 421 
 422 <p>For example, when working with radio buttons, it is common to define a <span class="code">ToggleGroup</span> that will manage the buttons' selection state. This group is not part of the scene graph itself, so should not be added to the buttons' parent. A define block can be used to create the button group without interfering with the overall structure of the document:</p>
 423 
 424 <pre class="code">
 425 &lt;VBox&gt;
 426     &lt;fx:define&gt;
 427         &lt;ToggleGroup fx:id="myToggleGroup"/&gt;
 428     &lt;/fx:define&gt;
 429     &lt;children&gt;
 430         &lt;RadioButton text="A" toggleGroup="$myToggleGroup"/&gt;
 431         &lt;RadioButton text="B" toggleGroup="$myToggleGroup"/&gt;
 432         &lt;RadioButton text="C" toggleGroup="$myToggleGroup"/&gt;
 433     &lt;/children&gt;
 434 &lt;/VBox&gt;
 435 </pre>
 436 
 437 <p>Elements in define blocks are usually assigned an ID that can be used to refer to the element's value later. IDs are discussed in more detail in later sections.</p>
 438 
 439 <h2><a name="attributes">Attributes</a></h2>
 440 <p>An attribute in FXML may represent one of the following:</p>
 441 <ul>
 442 <li>A property of a class instance</li>
 443 <li>A "static" property</li>
 444 <li>An event handler</li>
 445 </ul>
 446 
 447 <p>Each are discussed in more detail in the following sections.</p>
 448 
 449 <h3><a name="instance_property_attributes">Instance Properties</a></h3>
 450 <p><assert id="instance_properties" group="instance_properties">Like property elements, attributes can also be used to configure the properties of a class instance.</assert> For example, the following markup creates a <span class="code">Button</span> whose text reads "Click Me!":</p>
 451 
 452 <pre class="code">
 453 &lt;?import javafx.scene.control.*?&gt;
 454 &lt;Button text="Click Me!"/&gt;
 455 </pre>
 456 
 457 <p><assert id="attributes_type_coercion" group="instance_properties">As with property elements, property attributes support type coercion.</assert> When the following markup is processed, the "x", "y", "width", and "height" values will be converted to doubles, and the "fill" value will be converted to a <span class="code">Color</span>:</p>
 458 
 459 <pre class="code">
 460 &lt;Rectangle fx:id="rectangle" x="10" y="10" width="320" height="240"
 461     fill="#ff0000"/&gt;
 462 </pre>
 463 
 464 <p>Unlike property elements, which are applied as they are processed, property attributes are not applied until the closing tag of their respective element is reached. This is done primarily to facilitate the case where an attribute value depends on some information that won't be available until after the element's content has been completely processed (for example, the selected index of a <span class="code">TabPane</span> control, which can't be set until all of the tabs have been added).</p>
 465 
 466 <p>Another key difference between property attributes and property elements in FXML is that attributes support a number of "resolution operators" that extend their functionality. The following operators are supported and are discussed in more detail below:</p>
 467 
 468 <ul>
 469 <li>Location resolution</li>
 470 <li>Resource resolution</li>
 471 <li>Variable resolution</li>
 472 </ul>
 473 
 474 <h4><a name="location_resolution">Location Resolution</a></h4>
 475 <p><assert id="location_resolution" group="instance_properties">As strings, XML attributes cannot natively represent typed location information such as a URL. However, it is often necessary to specify such locations in markup; for example, the source of an image resource. The location resolution operator (represented by an "@" prefix to the attribute value) is used to specify that an attribute value should be treated as a location relative to the current file rather than a simple string.</assert></p>
 476 
 477 <p>For example, the following markup creates an ImageView and populates it with image data from <span class="filename">my_image.png</span>, which is assumed to be located at a path relative to the current FXML file:</p>
 478 
 479 <pre class="code">
 480 &lt;ImageView&gt;
 481     &lt;image&gt;
 482         &lt;Image url="@my_image.png"/&gt;
 483     &lt;/image&gt;
 484 &lt;/ImageView&gt;
 485 </pre>
 486 
 487 <p>Since <span class="code">Image</span> is an immutable object, a builder is required to construct it. Alternatively, if <span class="code">Image</span> were to define a <span class="code">valueOf(URL)</span> factory method, the image view could be populated as follows:</p>
 488 
 489 <pre class="code">
 490 &lt;ImageView image="@my_image.png"/&gt;
 491 </pre>
 492 
 493 <p>The value of the "image" attribute would be converted to a URL by the FXML loader, then coerced to an <span class="code">Image</span> using the <span class="code">valueOf()</span> method.</p>
 494 
 495 <p>Note that whitespace values in the URL must be encoded; for example, to refer to a file named "My Image.png", the FXML document should contain the following:</p>
 496 
 497 <pre class="code">
 498 &lt;Image url="@My%20Image.png"/&gt;
 499 </pre>
 500 
 501 <p>rather than:</p>
 502 
 503 <pre class="code">
 504 &lt;Image url="@My Image.png"/&gt;
 505 </pre>
 506 
 507 <h4><a name="resource_resolution">Resource Resolution</a></h4>
 508 <assert id="resource_resolution" group="instance_properties">
 509 <p>In FXML, resource substitution can be performed at load time for localization purposes. When provided with an instance of <span class="code">java.util.ResourceBundle</span>, the FXML loader will replace instances of resource names with their locale-specific values. Resource names are identified by a "%" prefix, as shown below:</p>
 510 
 511 <pre class="code">
 512 &lt;Label text="%myText"/&gt;
 513 </pre>
 514 
 515 <p>If the loader is given a resource bundle defined as follows:</p>
 516 
 517 <pre class="code">
 518 myText = This is the text!
 519 </pre>
 520 </assert>
 521 
 522 <p>the output of the FXML loader would be a <span class="code">Label</span> instance containing the text "This is the text!".</p>
 523 
 524 <h4><a name="variable_resolution">Variable Resolution</a></h4>
 525 <p><assert id="variable_resolution" group="instance_properties">An FXML document defines a variable namespace in which named elements and script variables may be uniquely identified. The variable resolution operator allows a caller to replace an attribute value with an instance of a named object before the corresponding setter method is invoked. Variable references are identified by a "$" prefix</assert>, as shown below:</p>
 526 
 527 <pre class="code">
 528 &lt;fx:define&gt;
 529     &lt;ToggleGroup fx:id="myToggleGroup"/&gt;
 530 &lt;/fx:define&gt;
 531 ...
 532 &lt;RadioButton text="A" toggleGroup="$myToggleGroup"/&gt;
 533 &lt;RadioButton text="B" toggleGroup="$myToggleGroup"/&gt;
 534 &lt;RadioButton text="C" toggleGroup="$myToggleGroup"/&gt;
 535 </pre>
 536 
 537 <p><assert id="assigning_id" group="instance_properties">Assigning an <span class="code">fx:id</span> value to an element creates a variable in the document's namespace that can later be referred to by variable dereference attributes, such as the "toggleGroup" attribute shown above, or in script code, discussed in a later section. Additionally, if the object's type defines an "id" property, this value will also be passed to the objects <span class="code">setId()</span> method.</assert></p>
 538 
 539 <h4><a name="escape_sequences">Escape Sequences</a></h4>
 540 
 541 <p><assert id="escape_sequences" group="instance_properties">If the value of an attribute begins with one of the resource resolution prefixes, the character can be escaped by prepending it with a leading backslash ("\") character.</assert> For example, the following markup creates a <span class="code">Label</span> instance whose text reads "$10.00":</p>
 542 
 543 <pre class="code">
 544 &lt;Label text="\$10.00"/&gt;
 545 </pre>
 546 
 547 <h4><a name="expression_binding">Expression Binding</a></h4>
 548 <p>Attribute variables as shown above are resolved once at load time. Later updates to the variables value are not automatically reflected in any properties to which the value was assigned. In many cases, this is sufficient; however, it is often convenient to "bind" a property value to a variable or expression such that changes to the variable are automatically propagated to the target property. Expression bindings can be used for this purpose.</p>
 549 
 550 <p><assert id="expression_binding" group="instance_properties">An expression binding also begins with the variable resolution operator, but is followed by a set of curly braces which wrap the expression value.</assert> For example, the following markup binds the value of a text input's "text" property to the "text" property of a <span class="code">Label</span> instance:</p>
 551 
 552 <pre class="code">
 553 &lt;TextField fx:id="textField"/&gt;
 554 &lt;Label text="${textField.text}"/&gt;
 555 </pre>
 556 
 557 <p>As the user types in the text input, the label's text content will be automatically updated.</p>
 558 
 559 <p>More complex expression are also supported. A list of supported constants and operators follows:</p>
 560 
 561 <table>
 562  <tr><td>"string"<br />'string'</td><td>A string constant</td></tr>
 563  <tr><td>true<br />false</td><td>A boolean constant</td></tr>
 564  <tr><td>null</td><td>A constant representing the null value</td></tr>
 565  <tr><td>50.0<br />3e5<br />42</td><td>A numerical constant</td></tr>
 566  <tr><td>- <br/>(unary operator)</td><td>Unary minus operator, applied on a number</td>
 567  <tr><td>! <br/>(unary operator)</td><td>Unary negation of a boolean</td></tr>
 568  <tr><td>+ - <br />
 569                         * /
 570                         %</td> <td>Numerical binary operators</td></tr>
 571  <tr><td>&& ||</td><td>Boolean binary operators</td></tr>
 572  <tr><td>&gt; &gt;= <br />
 573                    &lt; &lt;= <br />
 574                    == !=</td>
 575                    <td>Binary operators of comparison.<br/> Both arguments must be of type Comparable</td></tr>
 576 </table>
 577 
 578 <h3><a name="static_property_attributes">Static Properties</a></h3>
 579 <p><assert id="static_property_attributes" group="attributes">Attributes representing static properties are handled similarly to static property elements and use a similar syntax.</assert> For example, the earlier <span class="code">GridPane</span> markup shown earlier to demonstrate static property elements could be rewritten as follows:</p>
 580 
 581 <pre class="code">
 582 &lt;GridPane&gt;
 583     &lt;children&gt;
 584         &lt;Label text="My Label" GridPane.rowIndex="0" GridPane.columnIndex="0"/&gt;
 585     &lt;/children&gt;
 586 &lt;/TabPane&gt;
 587 </pre>
 588 
 589 <p><assert id="static_property_attributes_use" group="attributes">In addition to being more concise, static property attributes, like instance property attributes, support location, resource, and variable resolution operators, the only limitation being that it is not possible to create an expression binding to a static property.</assert></p>
 590 
 591 <h3><a name="event_handler_attributes">Event Handlers</a></h3>
 592 <p>Event handler attributes are a convenient means of attaching behaviors to document elements. Any class that defines a <span class="code">setOn<span class="variable">Event</span>()</span> method can be assigned an event handler in markup.</p>
 593 
 594 <p>FXML supports three types of event handler attributes: script event handlers, controller method event handlers and expressions. Each are discussed below.</p>
 595 
 596 <h4><a name="script_event_handlers">Script Event Handlers</a></h4>
 597 <p><assert id="script_event_handlers" group="event_handlers">A script event handler is an event handler that executes script code when the event is fired, similar to event handlers in HTML.</assert> For example, the following script-based handler for the button's "onAction" event uses JavaScript to write the text "You clicked me!" to the console when the user presses the button:</p>
 598 
 599 <pre class="code">
 600 &lt;?language javascript?&gt;
 601 ...
 602 
 603 &lt;VBox&gt;
 604     &lt;children&gt;
 605         &lt;Button text="Click Me!"
 606             onAction="java.lang.System.out.println('You clicked me!');"/&gt;
 607     &lt;/children&gt;
 608 &lt;/VBox&gt;
 609 </pre>
 610 
 611 <p><assert id="language_processing_instruction" group="event_handlers">Note the use of the language processing instruction at the beginning of the code snippet. This PI tells the FXML loader which scripting language should be used to execute the event handler. A page language must be specified whenever inline script is used in an FXML document, and can only be specified once per document. However, this does not apply to external scripts, which may be implemented using any number of supported scripting languages.</assert> Scripting is discussed in more detail in the next section.</p>
 612 
 613 <h4><a name="controller_method_event_handlers">Controller Method Event Handlers</a></h4>
 614 <p>A controller method event handler is a method defined by a document's "controller". A controller is an object that is associated with the deserialized contents of an FXML document and is responsible for coordinating the behaviors of the objects (often user interface elements) defined by the document.</p>
 615 
 616 <p><assert id="controller_method_event_handler_specification" group="event_handlers">A controller method event handler is specified by a leading hash symbol followed by the name of the handler method.</assert> For example:</p>
 617 
 618 <pre class="code">
 619 &lt;VBox fx:controller="com.foo.MyController"
 620     xmlns:fx="http://javafx.com/fxml"&gt;
 621     &lt;children&gt;
 622         &lt;Button text="Click Me!" onAction="#handleButtonAction"/&gt;
 623     &lt;/children&gt;
 624 &lt;/VBox&gt;
 625 </pre>
 626 
 627 <p><assert id="controller_attribute" group="event_handlers">Note the use of the <span class="code">fx:controller</span> attribute on the root element. This attribute is used to associate a controller class with the document.</assert> If <span class="code">MyController</span> is defined as follows:</p>
 628 
 629 <pre class="code">
 630 package com.foo;
 631 
 632 public class MyController {
 633     public void handleButtonAction(ActionEvent event) {
 634         System.out.println("You clicked me!");
 635     }
 636 }
 637 </pre>
 638 
 639 <p>the <span class="code">handleButtonAction()</span> will be called when the user presses the button, and the text "You clicked me!" will be written to the console.</p>
 640 
 641 <p><assert id="handler_method_signature" group="event_handlers">In general, a handler method should conform to the signature of a standard event handler; that is, it should take a single argument of a type that extends <span class="code">javafx.event.Event</span> and should return void (similar to an event delegate in C#). The event argument often carries important and useful information about the nature of the event;</assert> <assert id="handler_method_opt_arg" group="event_handlers">however, it is optional and may be omitted if desired</assert>.
 642 So this is also a valid handler:</p>
 643 
 644 <pre class="code">
 645 package com.foo;
 646 
 647 public class MyController {
 648     public void handleButtonAction() {
 649         System.out.println("You clicked me!");
 650     }
 651 }
 652 </pre>
 653 
 654 <p>Controllers are discussed in more detail in a later section.</p>
 655 
 656 <h4><a name="expression_handlers">Event handlers from expressions</a></h4>
 657 <p>Any expression that point to a <a href="#variable_resolution">variable</a> of javafx.event.EventHandler type
 658     can be used as an expression handler. </p>
 659 <p>
 660 Previous example using an expression handler:
 661 </p>


 667     &lt;/children&gt;
 668 &lt;/VBox&gt;
 669 </pre>
 670 
 671 <p> With the controller that contains a field like this </p>
 672     
 673 <pre class="code">
 674 public class MyController {
 675     
 676     @FXML
 677     public EventHandler<ActionEvent> onActionHandler = new EventHandler<>() { ... }
 678 
 679     ...
 680 }  
 681 </pre>
 682 
 683 <p> Note that other kinds of expressions, like <a href="#expression_binding">binding expressions</a>
 684     are not supported in this context. </p>
 685 
 686 <h4><a name="collections_and_property_handlers">Special handlers for collections and properties</a></h4>
 687 <p> Collections and object properties cannot be listen to using <span class="code">setOn<span class="variable">Event</span>()</span> methods.
 688     For these reason, special handler methods need to be used.
 689 <span class="code">ObservableList</span>, <span class="code">ObservableMap</span> or <span class="code">ObservableSet</span>
 690  uses a special <span class="code">onChange</span> attribute that points to a handler method with a <span class="code">ListChangeListner.Change</span>, <span class="code">MapChangeListener.Change</span> or <span class="code">SetChangeListener.Change</span> parameter respectively.
 691 </p>
 692 <pre class="code">
 693 &lt;VBox fx:controller="com.foo.MyController"
 694     xmlns:fx="http://javafx.com/fxml"&gt;
 695     &lt;children onChange="#handleChildrenChange"/&gt;
 696 &lt;/VBox&gt;
 697 </pre>
 698 
 699 where the handler method looks like this:
 700 
 701 <pre class="code">
 702 package com.foo;
 703 
 704 import javafx.collections.ListChangeListener.Change;
 705 
 706 public class MyController {
 707     public void handleChildrenChange(ListChangeListener.Change c) {
 708         System.out.println("Children changed!");
 709     }
 710 }
 711 </pre>
 712 
 713 <p>Similarly, the property handlers are methods that have the same parameters as changed method of ChangeListener :</p>
 714 <p><span class="code">changed(ObservableValue&lt;? extends T&gt; observable, T oldValue, T newValue)</span></p>
 715 
 716 <p>A handler for parent property would look like this</p>
 717 <pre class="code">
 718 public class MyController {
 719     public void handleParentChange(ObservableValue value, Parent oldValue, Parent newValue) {
 720         System.out.println("Parent changed!");
 721     }
 722 }
 723 </pre>
 724 
 725 <p>For convenience, the first parameter can be a subclass of <span class="code">ObservableValue</span>,
 726     e.g. <span class="code">Property</span></p>
 727 
 728 <p>For registering to a property, a special <span class="code">on&lt;propertyName&gt;Change</span>
 729 attribute must be used.</p>
 730 
 731 <pre class="code">
 732 &lt;VBox fx:controller="com.foo.MyController"
 733     xmlns:fx="http://javafx.com/fxml" onParentChange="#handleParentChange"/&gt;
 734 </pre>
 735     
 736 <p>Note that collections and properties do not currently support scripting handlers.</p>
 737 
 738 <h2><a name="scripting">Scripting</a></h2>
 739 <assert id="script_tag" group="scripting">The <span class="code">&lt;fx:script&gt;</span> tag allows a caller to import scripting code into or embed script within a FXML file. Any JVM scripting language can be used, including JavaScript, Groovy, and Clojure, among others. Script code is often used to define event handlers directly in markup or in an associated source file, since event handlers can often be written more concisely in more loosely-typed scripting languages than they can in a statically-typed language such as Java.</assert></p>
 740 
 741 <p>For example, the following markup defines a function called <span class="code">handleButtonAction()</span> that is called by the action handler attached to the <span class="code">Button</span> element:</p>
 742 
 743 <pre class="code">
 744 &lt;?language javascript?&gt;
 745 
 746 &lt;?import javafx.scene.control.*?&gt;
 747 &lt;?import javafx.scene.layout.*?&gt;
 748 
 749 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 750     &lt;fx:script&gt;
 751 
 752     function handleButtonAction(event) {
 753        java.lang.System.out.println('You clicked me!');
 754     }
 755     &lt;/fx:script&gt;
 756 
 757     &lt;children&gt;
 758         &lt;Button text="Click Me!" onAction="handleButtonAction(event);"/&gt;
 759     &lt;/children&gt;
 760 &lt;/VBox&gt;
 761 </pre>


 772 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 773     &lt;fx:script source="example.js" charset="cp1252"/&gt;
 774 
 775     &lt;children&gt;
 776         &lt;Button text="Click Me!" onAction="handleButtonAction(event);"/&gt;
 777     &lt;/children&gt;
 778 &lt;/VBox&gt;
 779 </pre>
 780 
 781 <div class="caption">example.js</div>
 782 <pre class="code">
 783 
 784 function handleButtonAction(event) {
 785    java.lang.System.out.println('You clicked me!');
 786 }
 787 </pre>
 788 
 789 <p>It is often preferable to separate code from markup in this way, since many text editors support syntax highlighting for the various scripting languages supported by the JVM. It can also help improve readability of the source code and markup.</p>
 790 
 791 <assert id="script_blocks_not_limited" group="scripting">
 792 <p>Note that script blocks are not limited to defining event handler functions. Script code is executed as it is processed, so it can also be used to dynamically configure the structure of the resulting output. As a simple example, the following FXML includes a script block that defines a variable named "labelText". The value of this variable is used to populate the text property of a <span class="code">Label</span> instance:</p>
 793 
 794 <pre class="code">
 795 &lt;fx:script&gt;
 796 var myText = "This is the text of my label.";
 797 &lt;/fx:script&gt;
 798 
 799 ...
 800 
 801 &lt;Label text="$myText"/&gt;
 802 </pre>
 803 </assert>
 804 
 805 <p><strong>Warning:</strong>As of JavaFX 8, <span class="code">importClass()</span> javascript function is no longer supported. You have to use fully qualified names as in the example above or load a nashorn compatibility script.</p>
 806 
 807 <pre class="code">
 808 load("nashorn:mozilla_compat.js");
 809 importClass(java.lang.System);
 810 
 811 function handleButtonAction(event) {
 812    System.out.println('You clicked me!');
 813 }
 814 </pre> 
 815 
 816 <h2><a name="controllers">Controllers</a></h2>
 817 <p>While it can be convenient to write simple event handlers in script, either inline or defined in external files, it is often preferable to define more complex application logic in a compiled, strongly-typed language such as Java. As discussed earlier, the <span class="code">fx:controller</span> attribute allows a caller to associate a "controller" class with an FXML document. A controller is a compiled class that implements the "code behind" the object hierarchy defined by the document.</p>
 818 
 819 <p>As shown earlier, controllers are often used to implement event handlers for user interface elements defined in markup:</p>
 820 
 821 <pre class="code">
 822 &lt;VBox fx:controller="com.foo.MyController"
 823     xmlns:fx="http://javafx.com/fxml"&gt;
 824     &lt;children&gt;
 825         &lt;Button text="Click Me!" onAction="#handleButtonAction"/&gt;
 826     &lt;/children&gt;
 827 &lt;/VBox&gt;
 828 </pre>
 829 
 830 <pre class="code">
 831 package com.foo;
 832 
 833 public class MyController {
 834     public void handleButtonAction(ActionEvent event) {
 835         System.out.println("You clicked me!");
 836     }
 837 }
 838 </pre>
 839 
 840 <p><assert id="handlers_initialize" group="controllers">In many cases, it is sufficient to simply declare event handlers in this manner. However, when more control over the behavior of the controller and the elements it manages is required, the controller can define an <span class="code">initialize()</span> method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded</assert>:</p>
 841 
 842 <pre class="code">
 843 public void initialize();
 844 </pre>
 845 
 846 <p><assert id="post-processing" group="controllers">This allows the implementing class to perform any necessary post-processing on the content.</assert> It also provides the controller with access to the resources that were used to load the document and the location that was used to resolve relative paths within the document (commonly equivalent to the location of the document itself).</p>
 847 
 848 <p>For example, the following code defines an <span class="code">initialize()</span> method that attaches an action handler to a button in code rather than via an event handler attribute, as was done in the previous example. The button instance variable is injected by the loader as the document is read. The resulting application behavior is identical:</p>
 849 
 850 <pre class="code">
 851 &lt;VBox fx:controller="com.foo.MyController"
 852     xmlns:fx="http://javafx.com/fxml"&gt;
 853     &lt;children&gt;
 854         &lt;Button fx:id="button" text="Click Me!"/&gt;
 855     &lt;/children&gt;
 856 &lt;/VBox&gt;
 857 </pre>
 858 
 859 <pre class="code">
 860 package com.foo;
 861 
 862 public class MyController implements Initializable {
 863     public Button button;
 864 
 865     @Override
 866     public void initialize(URL location, Resources resources)
 867         button.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
 868             @Override
 869             public void handle(ActionEvent event) {
 870                 System.out.println("You clicked me!");
 871             }
 872         });
 873     }
 874 }
 875 </pre>
 876 
 877 <h3><a name="fxml_annotation">@FXML</a></h3>
 878 <p><assert id="public_controller_access" group="controllers">Note
 879 that, in the previous examples, the controller member fields and
 880 event handler methods were declared as public so they can be set
 881 or invoked by the loader.</assert> In practice, this is not often
 882 an issue, since a controller is generally only visible to the FXML
 883 loader that creates it. <assert id="FXML_controller_access"
 884 group="controllers">However, for developers who prefer more restricted
 885 visibility for controller fields or handler methods, the <span
 886 class="code">javafx.fxml.FXML</span> annotation can be used. This
 887 annotation marks a protected or private class member as accessible
 888 to FXML.
 889 If the class being annotated is part of a named module, the
 890 module containing that class must <span class="code">open</span>
 891 the containing package to
 892 the <span class="code">javafx.fxml</span> module.</assert></span>
 893 
 894 <p>For example, the controllers from the previous examples could be rewritten as follows:</p>
 895 
 896 <pre class="code">
 897 package com.foo;
 898 
 899 public class MyController {
 900     @FXML
 901     private void handleButtonAction(ActionEvent event) {
 902         System.out.println("You clicked me!");
 903     }
 904 }
 905 </pre>
 906 
 907 <pre class="code">
 908 package com.foo;
 909 
 910 public class MyController implements Initializable {
 911     @FXML private Button button;
 912 
 913     @FXML
 914     protected void initialize()
 915         button.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
 916             @Override
 917             public void handle(ActionEvent event) {
 918                 System.out.println("You clicked me!");
 919             }
 920         });
 921     }
 922 }
 923 </pre>
 924 
 925 <p>In the first version, the <span class="code">handleButtonAction()</span> is tagged with <span class="code">@FXML</span> to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The <span class="code">initialize()</span> method is similarly annotated.</p>


 926 
 927 <h3><a name="nested_controllers">Nested Controllers</a></h3>
 928 <p><assert id="nested_fxml_mapping" group="controllers">Controller instances for nested FXML documents loaded via the <span class="code">&lt;fx:include&gt;</span> element are mapped directly to member fields of the including controller.</assert> This allows a developer to easily access functionality defined by an include (such as a dialog window presented by an application's main window controller). For example, given the following code:
 929 
 930 <div class="caption">main_window_content.fxml</div>
 931 <pre class="code">
 932 &lt;VBox fx:controller="com.foo.MainController"&gt;
 933    &lt;fx:define&gt;
 934       &lt;fx:include fx:id="dialog" source="dialog.fxml"/&gt;
 935    &lt;/fx:define&gt;
 936    ...
 937 &lt;/VBox&gt;
 938 </pre>
 939 
 940 <div class="caption">MainController.java</div>
 941 <pre class="code">
 942 public class MainController extends Controller {
 943     @FXML private Window dialog;
 944     @FXML private DialogController dialogController;
 945 
 946     ...
 947 }
 948 </pre>
 949 
 950 <p>when the controller's <span class="code">initialize()</span> method is called, the <span class="code">dialog</span> field will contain the root element loaded from the "dialog.fxml" include, and the <span class="code">dialogController</span> field will contain the include's controller. The main controller can then invoke methods on the included controller, to populate and show the dialog, for example. Note that as the content of the file referenced by fx:include otherwise would become part of the scene graph spanned from main_window_content.fxml, it is necessary to wrap fx:include by fx:define to separate the scene graphs of both windows.</p>
 951 
 952 <h2><a name="fxmlloader">FXMLLoader</a></h2>
 953 <p>The <span class="code">FXMLLoader</span> class is responsible for actually loading an FXML source file and returning the resulting object graph. For example, the following code loads an FXML file from a location on the classpath relative to the loading class and localizes it with a resource bundle named "com.foo.example". The type of the root element is assumed to be a subclass of <span class="code">javafx.scene.layout.Pane</span>, and the document is assumed to define a controller of type <span class="code">MyController</span>:</p>
 954 
 955 <pre class="code">
 956 URL location = getClass().getResource("example.fxml");
 957 ResourceBundle resources = ResourceBundle.getBundle("com.foo.example");
 958 FXMLLoader fxmlLoader = new FXMLLoader(location, resources);
 959 
 960 Pane root = (Pane)fxmlLoader.load();
 961 MyController controller = (MyController)fxmlLoader.getController();
 962 </pre>
 963 
 964 <p><assert id="loader_instance_hierarchy" group="fxml_loader">Note that the output of an <span class="code">FXMLLoader#load()</span> operation is an instance hierarchy that reflects the actual named classes in the document, not <span class="code">org.w3c.dom</span> nodes representing those classes.</assert> Internally, <span class="code">FXMLLoader</span> uses the <span class="code">javax.xml.stream</span> API (also known as the <i>Streaming API for XML</i>, or <i>StAX</i>) to load an FXML document. StAX is an extremely efficient event-based XML parsing API that is conceptually similar to its W3C predecessor, SAX. It allows an FXML document to be processed in a single pass, rather than loaded into an intermediate DOM structure and then post-processed.</p>
 965 
 966 <h3><a name="custom_components">Custom Components</a></h3>
 967 <p>The <assert id="loader_setRoot" group="fxml_loader"><span class="code">setRoot()</span></assert> and <assert id="loader_setController" group="fxml_loader"><span class="code">setController()</span></assert> methods of <span class="code">FXMLLoader</span> allow a caller to inject document root and controller values, respectively, into the document namespace, rather than delegating creation of these values to <span class="code">FXMLLoader</span> itself. This allows a developer to easily create reusable controls that are internally implemented using markup, but (from an API perspective) appear identically to controls implemented programmatically.</p>
 968 
 969 <p>For example, the following markup defines the structure of a simple custom control containing a <span class="code">TextField</span> and a <span class="code">Button</span> instance. The root container is defined as an instance of <span class="code">javafx.scene.layout.VBox</span>:</p>
 970 
 971 <pre class="code">
 972 &lt;?import javafx.scene.*?&gt;
 973 &lt;?import javafx.scene.control.*?&gt;
 974 &lt;?import javafx.scene.layout.*?&gt;
 975 
 976 &lt;fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml"&gt;
 977     &lt;TextField fx:id="textField"/&gt;
 978     &lt;Button text="Click Me" onAction="#doSomething"/&gt;
 979 &lt;/fx:root&gt;
 980 </pre>
 981 
 982 <p>As mentioned earlier, the <span class="code">&lt;fx:root&gt;</span> tag creates a reference to a previously defined root element. The value of this element is obtained by calling the <span class="code">getRoot()</span> method of <span class="code">FXMLLoader</span>. <assert id="loader_setRoot_sequence" group="fxml_loader">Prior to calling <span class="code">load()</span>, the caller must specify this value via a call to <span class="code">setRoot()</span></assert>. <assert id="loader_setController_sequence" group="fxml_loader">The caller may similarly provide a value for the document's controller by calling <span class="code">setController()</span>, which sets the value that will be used as the document's controller when the document is read</assert>. These two methods are commonly used together when creating custom FXML-based components.</p>
 983 
 984 <p>In the following example, the <span class="code">CustomControl</span> class extends <span class="code">VBox</span> (the type declared by the <span class="code">&lt;fx:root&gt;</span> element), and sets itself as both the root and controller of the FXML document in its constructor. When the document is loaded, the contents of <span class="code">CustomControl</span> will be populated with the contents of the previous FXML document:</p>
 985 
 986 <pre class="code">
 987 package fxml;
 988 
 989 import java.io.IOException;
 990 
 991 import javafx.beans.property.StringProperty;
 992 import javafx.fxml.FXML;
 993 import javafx.fxml.FXMLLoader;
 994 import javafx.scene.control.TextField;
 995 import javafx.scene.layout.VBox;
 996 
 997 public class CustomControl extends VBox {
 998     @FXML private TextField textField;
 999 
1000     public CustomControl() {
1001         FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("custom_control.fxml"));
1002         fxmlLoader.setRoot(this);
1003         fxmlLoader.setController(this);
1004 


< prev index next >