1 <!doctype html>
   2 
   3 <!--
   4 /*
   5  * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.  Oracle designates this
  11  * particular file as subject to the "Classpath" exception as provided
  12  * by Oracle in the LICENSE file that accompanied this code.
  13  *
  14  * This code is distributed in the hope that it will be useful, but WITHOUT
  15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  16  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  17  * version 2 for more details (a copy is included in the LICENSE file that
  18  * accompanied this code).
  19  *
  20  * You should have received a copy of the GNU General Public License version
  21  * 2 along with this work; if not, write to the Free Software Foundation,
  22  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  23  *
  24  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  25  * or visit www.oracle.com if you need additional information or have any
  26  * questions.
  27  */
  28 -->
  29 
  30 <html lang="en">
  31 <head>
  32 <link href="fxml.css" type="text/css" rel="stylesheet"/>    
  33 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  34 <title>Introduction to FXML | JavaFX @FXVERSION@</title>
  35 <meta name="description" content="The document introduces FXML, an XML-based declarative markup language for defining user interfaces in JavaFX @FXVERSION@ applications."/>
  36 <meta name="keywords" content="JavaFX, FXML, JavaFX GUI development, web development, Java application development, GUI applications, rich internet applications, RIA, expressive content"/>
  37 </head>
  38 <body>
  39 
  40 <div class="fx-code-header">
  41 <div class="version"><br/>Release: JavaFX @FXVERSION@</div>
  42 </div>
  43 
  44 <h1>Introduction to FXML</h1>
  45 <p class="subtitle">Last updated: 01 May 2017</p>
  46 
  47 <h2>Contents</h2>
  48 <ul class="contents">
  49 <li><a href="#overview">Overview</a></li>
  50 <li>
  51     <a href="#elements">Elements</a>
  52     <ul>
  53     <li>
  54         <a href="#class_instance_elements">Class Instance Elements</a>
  55         <ul>
  56         <li><a href="#instance_declaration_elements">Instance Declarations</a></li>
  57         <li><a href="#include_elements">&lt;fx:include&gt;</a></li>
  58         <li><a href="#constant_elements">&lt;fx:constant&gt;</a></li>
  59         <li><a href="#reference_elements">&lt;fx:reference&gt;</a></li>
  60         <li><a href="#copy_elements">&lt;fx:copy&gt;</a></li>
  61         <li><a href="#root_elements">&lt;fx:root&gt;</a></li>
  62         </ul>
  63     </li>
  64 
  65     <li>
  66         <a href="#property_elements">Property Elements</a>
  67         <ul>
  68         <li><a href="#property_setter_elements">Property Setters</a></li>
  69         <li><a href="#read_only_list_property_elements">Read-Only List Properties</a></li>
  70         <li><a href="#read_only_map_property_elements">Read-Only Map Properties</a></li>
  71         <li><a href="#default_properties">Default Properties</a></li>
  72         </ul>
  73     </li>
  74 
  75     <li><a href="#static_property_elements">Static Properties</a></li>
  76     <li><a href="#define_elements">Define Blocks</a></li>
  77     </ul>
  78 </li>
  79 <li>
  80     <a href="#attributes">Attributes</a>
  81     <ul>
  82     <li>
  83         <a href="#instance_property_attributes">Instance Properties</a>
  84         <ul>
  85         <li><a href="#location_resolution">Location Resolution</a></li>
  86         <li><a href="#resource_resolution">Resource Resolution</a></li>
  87         <li><a href="#variable_resolution">Variable Resolution</a></li>
  88         <li><a href="#escape_sequences">Escape Sequences</a></li>
  89         <li><a href="#expression_binding">Expression Binding</a></li>
  90         </ul>
  91     </li>
  92 
  93     <li><a href="#static_property_attributes">Static Properties</a></li>
  94     <li>
  95         <a href="#event_handler_attributes">Event Handlers</a>
  96         <ul>
  97         <li><a href="#script_event_handlers">Script Event Handlers</a></li>
  98         <li><a href="#controller_method_event_handlers">Controller Method Event Handlers</a></li>
  99         <li><a href="#expression_handlers">Event handlers from expressions</a></li>
 100         <li><a href="#collections_and_property_handlers">Special handlers for collections and properties</a></li>
 101         </ul>
 102     </li>
 103     </ul>
 104 </li>
 105 <li><a href="#scripting">Scripting</a></li>
 106 <li>
 107     <a href="#controllers">Controllers</a>
 108     <ul>
 109     <li><a href="#fxml_annotation">@FXML</a></li>
 110     <li><a href="#nested_controllers">Nested Controllers</a></li>
 111     </ul>
 112 </li>
 113 <li>
 114     <a href="#fxmlloader">FXMLLoader</a>
 115     <ul>
 116     <li><a href="#custom_components">Custom Components</a></li>
 117     </ul>
 118 </li>
 119 <li><a href="#deploy_as_module">Deploying an Application as a Module</a></li>
 120 </ul>
 121 
 122 <h2><a id="overview">Overview</a></h2>
 123 <p>FXML is a scriptable, XML-based markup language for constructing Java object graphs. It provides a convenient alternative to constructing such graphs in procedural code, and is ideally suited to defining the user interface of a JavaFX application, since the hierarchical structure of an XML document closely parallels the structure of the JavaFX scene graph.</p>
 124 
 125 <p>This document introduces the FXML markup language and explains how it can be used to simplify development of JavaFX applications.</p>
 126 
 127 <h2><a id="elements">Elements</a></h2>
 128 <p>In FXML, an XML element represents one of the following:</p>
 129 <ul>
 130 <li>A class instance</li>
 131 <li>A property of a class instance</li>
 132 <li>A "static" property</li>
 133 <li>A "define" block</li>
 134 <li>A block of script code</li>
 135 </ul>
 136 
 137 <p>Class instances, instance properties, static properties, and define blocks are discussed in this section below. Scripting is discussed in a later section.</p>
 138 
 139 <h3><a id="class_instance_elements">Class Instance Elements</a></h3>
 140 <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>
 141 
 142 <h4><a id="instance_declaration_elements">Instance Declarations</a></h4>
 143 <p>If an element's tag is considered an instance declaration if the tag begins with uppercase letter (and the class is imported) or, as in Java, it denotes a fully-qualified (including the package name) name of a class. When the FXML loader (also introduced later) encounters such an element, it creates an instance of that class.</p>
 144 
 145 <p>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>
 146 
 147 <pre class="code">
 148 &lt;?import javafx.scene.control.Label?&gt;
 149 </pre>
 150 
 151 <p>This PI imports all classes from the javafx.scene.control package into the current namespace:</p>
 152 
 153 <pre class="code">
 154 &lt;?import javafx.scene.control.*?&gt;
 155 </pre>
 156 
 157 
 158 <p>Any class that adheres to JavaBean constructor and property naming conventions can be readily instantiated and configured using FXML. 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>
 159 
 160 <pre class="code">
 161 &lt;?import javafx.scene.control.Label?&gt;
 162 &lt;Label text="Hello, World!"/&gt;
 163 </pre>
 164 
 165 <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>
 166 
 167 <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>
 168 
 169 <h5>Maps</h5>
 170 <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>
 171 
 172 <p>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. 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:
 173 
 174 <pre class="code">
 175 &lt;HashMap foo="123" bar="456"/&gt;
 176 </pre>
 177 
 178 <h5>fx:value</h5>
 179 <p>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. 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>
 180 
 181 <pre class="code">
 182 &lt;String fx:value="Hello, World!"/&gt;
 183 &lt;Double fx:value="1.0"/&gt;
 184 &lt;Boolean fx:value="false"/&gt;
 185 </pre>
 186 
 187 <p>Custom classes that define a static <span class="code">valueOf(String)</span> method can also be constructed this way.</p>
 188 
 189 <h5>fx:factory</h5>
 190 <p>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. For example, the following markup creates an instance of an observable array list, populated with three string values:</p>
 191 
 192 <pre class="code">
 193 &lt;FXCollections fx:factory="observableArrayList"&gt;
 194     &lt;String fx:value="A"/&gt;
 195     &lt;String fx:value="B"/&gt;
 196     &lt;String fx:value="C"/&gt;
 197 &lt;/FXCollections&gt;
 198 </pre>
 199 
 200 <h5>Builders</h5>
 201 <p>A third means of creating instances of classes that do not conform to Bean conventions (such as those representing immutable values) is a "builder". 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>
 202 
 203 <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>
 204 
 205 <pre class="code">
 206 public interface Builder&lt;T&gt; {
 207     public T build();
 208 }
 209 </pre>
 210 
 211 <p>A <span class="code">javafx.util.BuilderFactory</span> is responsible for producing builders that are capable of instantiating a given type:</p>
 212 
 213 <pre class="code">
 214 public interface BuilderFactory {
 215     public Builder&lt;?&gt; getBuilder(Class&lt;?&gt; type);
 216 }
 217 </pre>
 218 
 219 <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:
 220 
 221 <pre class="code">
 222 &lt;Color red="1.0" green="0.0" blue="0.0"/&gt;
 223 </pre>
 224 
 225 <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>
 226 
 227 <pre class="code">
 228 &lt;Color&gt;
 229     &lt;red&gt;1.0&lt;/red&gt;
 230     &lt;green&gt;0.0&lt;/green&gt;
 231     &lt;blue&gt;0.0&lt;/blue&gt;
 232 &lt;/Color&gt;
 233 </pre>
 234 
 235 <p>The <span class="code">Color</span> instance cannot be fully constructed until all three of the color components are known.</p>
 236 
 237 <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>
 238 
 239 <h4><a id="include_elements">&lt;fx:include&gt;</a></h4>
 240 <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>
 241 
 242 <pre class="code">
 243 &lt;fx:include source="<span class="variable">filename</span>"/&gt;
 244 </pre>
 245 
 246 <p>where <span class="variable">filename</span> is the name of the FXML file to include. Values that begin with a leading slash character are treated as relative to the classpath. Values with no leading slash are considered relative to the path of the current document.</p>
 247 
 248 <p>For example, given the following markup:</p>
 249 
 250 <pre class="code">
 251 &lt;?import javafx.scene.control.*?&gt;
 252 &lt;?import javafx.scene.layout.*?&gt;
 253 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 254     &lt;children&gt;
 255         &lt;fx:include source="my_button.fxml"/&gt;
 256     &lt;/children&gt;
 257 &lt;/VBox&gt;
 258 </pre>
 259 
 260 <p>If <span class="filename">my_button.fxml</span> contains the following:
 261 
 262 <pre class="code">
 263 &lt;?import javafx.scene.control.*?&gt;
 264 &lt;Button text="My Button"/&gt;
 265 </pre>
 266 
 267 <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>
 268 
 269 <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>
 270 
 271 <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>
 272 
 273 <pre class="code">
 274 &lt;fx:include source="<span class="variable">filename</span>" resources="<span class="variable">resource_file</span>" charset="utf-8"/&gt;
 275 </pre>
 276 
 277 <h4><a id="constant_elements">&lt;fx:constant&gt;</a></h4>
 278 <p>The <span class="code">&lt;fx:constant&gt;</span> element creates a reference to a class constant. 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>
 279 
 280 <pre class="code">
 281 &lt;Button&gt;
 282     &lt;minHeight&gt;&lt;Double fx:constant="NEGATIVE_INFINITY"/&gt;&lt;/minHeight&gt;
 283 &lt;/Button&gt;
 284 </pre>
 285 
 286 <h4><a id="reference_elements">&lt;fx:reference&gt;</a></h4>
 287 <p>The <span class="code">&lt;fx:reference&gt;</span> element creates a new reference to an existing element. 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>
 288 
 289 <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>
 290 
 291 <pre class="code">
 292 &lt;ImageView&gt;
 293     &lt;image&gt;
 294         &lt;fx:reference source="myImage"/&gt;
 295     &lt;/image&gt;
 296 &lt;/ImageView&gt;
 297 </pre>
 298 
 299 <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>
 300 
 301 <pre class="code">
 302 &lt;ArrayList&gt;
 303     &lt;fx:reference source="element1"/&gt;
 304     &lt;fx:reference source="element2"/&gt;
 305     &lt;fx:reference source="element3"/&gt;
 306 &lt;/ArrayList&gt;
 307 </pre>
 308 
 309 <p>For most other cases, using an attribute is simpler and more concise.</p>
 310 
 311 <h4><a id="copy_elements">&lt;fx:copy&gt;</a></h4>
 312 <p>The <span class="code">&lt;fx:copy&gt;</span> element creates a copy of an existing element. 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>
 313 
 314 <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>
 315 
 316 <h4><a id="root_elements">&lt;fx:root&gt;</a></h4>
 317 <p>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. <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>
 318 
 319 <h3><a id="property_elements">Property Elements</a></h3>
 320 <p>Elements whose tag names begin with a lowercase letter represent object properties. A property element may represent one of the following:</p>
 321 
 322 <ul>
 323 <li>A property setter</li>
 324 <li>A read-only list property</li>
 325 <li>A read-only map property</li>
 326 </ul>
 327 
 328 <h4><a id="property_setter_elements">Property Setters</a></h4>
 329 <p>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.</p>
 330 
 331 <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>
 332 
 333 <pre class="code">
 334 &lt;?import javafx.scene.control.Label?&gt;
 335 &lt;Label&gt;
 336     &lt;text&gt;Hello, World!&lt;/text&gt;
 337 &lt;/Label&gt;
 338 </pre>
 339 
 340 <p>This produces the same result as the earlier example which used an attribute to set the "text" property:</p>
 341 
 342 <pre class="code">
 343 &lt;?import javafx.scene.control.Label?&gt;
 344 &lt;Label text="Hello, World!"/&gt;
 345 </pre>
 346 
 347 <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>
 348 
 349 <h5>Type Coercion</h5>
 350 <p>FXML uses "type coercion" to convert property values to the appropriate type as needed. 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>
 351 
 352 <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>
 353 
 354 <h4><a id="read_only_list_property_elements">Read-Only List Properties</a></h4>
 355 <p>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.</p>
 356 
 357 <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>
 358 
 359 <pre class="code">
 360 &lt;?import javafx.scene.*?&gt;
 361 &lt;?import javafx.scene.shape.*?&gt;
 362 &lt;Group xmlns:fx="http://javafx.com/fxml"&gt;
 363     &lt;children&gt;
 364         &lt;Rectangle fx:id="rectangle" x="10" y="10" width="320" height="240"
 365             fill="#ff0000"/&gt;
 366         ...
 367     &lt;/children&gt;
 368 &lt;/Group&gt;
 369 </pre>
 370 
 371 <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>.
 372 
 373 <h4><a id="read_only_map_property_elements">Read-Only Map Properties</a></h4>
 374 <p>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.</p>
 375 
 376 <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>
 377 
 378 <pre class="code">
 379 &lt;?import javafx.scene.control.*?&gt;
 380 &lt;Button&gt;
 381     &lt;properties foo="123" bar="456"/&gt;
 382 &lt;/Button&gt;
 383 </pre>
 384 
 385 <p>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.</p>
 386 
 387 <h4><a id="default_properties">Default Properties</a></h4>
 388 <p>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.</p>
 389 
 390 <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>
 391 
 392 <pre class="code">
 393 &lt;?import javafx.scene.*?&gt;
 394 &lt;?import javafx.scene.shape.*?&gt;
 395 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 396     &lt;Button text="Click Me!"/&gt;
 397     ...
 398 &lt;/VBox&gt;
 399 </pre>
 400 
 401 <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>
 402 
 403 <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:
 404 
 405 <pre class="code">
 406 &lt;ScrollPane&gt;
 407     &lt;TextArea text="Once upon a time..."/&gt;
 408 &lt;/ScrollPane&gt;
 409 </pre>
 410 
 411 <p>Taking advantage of default properties can significantly reduce the verbosity of FXML markup.</p>
 412 
 413 <h3><a id="static_property_elements">Static Properties</a></h3>
 414 <p>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).</p>
 415 
 416 <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>
 417 
 418 <pre class="code">
 419 &lt;GridPane&gt;
 420     &lt;children&gt;
 421         &lt;Label text="My Label"&gt;
 422             &lt;GridPane.rowIndex&gt;0&lt;/GridPane.rowIndex&gt;
 423        &lt;GridPane.columnIndex&gt;0&lt;/GridPane.columnIndex&gt;
 424         &lt;/Label&gt;
 425     &lt;/children&gt;
 426 &lt;/TabPane&gt;
 427 </pre>
 428 
 429 <p>This translates roughly to the following in Java:</p>
 430 
 431 <pre class="code">
 432 GridPane gridPane = new GridPane();
 433 
 434 Label label = new Label();
 435 label.setText("My Label");
 436 
 437 GridPane.setRowIndex(label, 0);
 438 GridPane.setColumnIndex(label, 0);
 439 
 440 gridPane.getChildren().add(label);
 441 </pre>
 442 
 443 <p>
 444 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>
 445 
 446 <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>
 447 
 448 <h3><a id="define_elements">Define Blocks</a></h3>
 449 <p>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.</p>
 450 
 451 <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>
 452 
 453 <pre class="code">
 454 &lt;VBox&gt;
 455     &lt;fx:define&gt;
 456         &lt;ToggleGroup fx:id="myToggleGroup"/&gt;
 457     &lt;/fx:define&gt;
 458     &lt;children&gt;
 459         &lt;RadioButton text="A" toggleGroup="$myToggleGroup"/&gt;
 460         &lt;RadioButton text="B" toggleGroup="$myToggleGroup"/&gt;
 461         &lt;RadioButton text="C" toggleGroup="$myToggleGroup"/&gt;
 462     &lt;/children&gt;
 463 &lt;/VBox&gt;
 464 </pre>
 465 
 466 <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>
 467 
 468 <h2><a id="attributes">Attributes</a></h2>
 469 <p>An attribute in FXML may represent one of the following:</p>
 470 <ul>
 471 <li>A property of a class instance</li>
 472 <li>A "static" property</li>
 473 <li>An event handler</li>
 474 </ul>
 475 
 476 <p>Each are discussed in more detail in the following sections.</p>
 477 
 478 <h3><a id="instance_property_attributes">Instance Properties</a></h3>
 479 <p>Like property elements, attributes can also be used to configure the properties of a class instance. For example, the following markup creates a <span class="code">Button</span> whose text reads "Click Me!":</p>
 480 
 481 <pre class="code">
 482 &lt;?import javafx.scene.control.*?&gt;
 483 &lt;Button text="Click Me!"/&gt;
 484 </pre>
 485 
 486 <p>As with property elements, property attributes support type coercion. 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>
 487 
 488 <pre class="code">
 489 &lt;Rectangle fx:id="rectangle" x="10" y="10" width="320" height="240"
 490     fill="#ff0000"/&gt;
 491 </pre>
 492 
 493 <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>
 494 
 495 <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>
 496 
 497 <ul>
 498 <li>Location resolution</li>
 499 <li>Resource resolution</li>
 500 <li>Variable resolution</li>
 501 </ul>
 502 
 503 <h4><a id="location_resolution">Location Resolution</a></h4>
 504 <p>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.</p>
 505 
 506 <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>
 507 
 508 <pre class="code">
 509 &lt;ImageView&gt;
 510     &lt;image&gt;
 511         &lt;Image url="@my_image.png"/&gt;
 512     &lt;/image&gt;
 513 &lt;/ImageView&gt;
 514 </pre>
 515 
 516 <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>
 517 
 518 <pre class="code">
 519 &lt;ImageView image="@my_image.png"/&gt;
 520 </pre>
 521 
 522 <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>
 523 
 524 <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>
 525 
 526 <pre class="code">
 527 &lt;Image url="@My%20Image.png"/&gt;
 528 </pre>
 529 
 530 <p>rather than:</p>
 531 
 532 <pre class="code">
 533 &lt;Image url="@My Image.png"/&gt;
 534 </pre>
 535 
 536 <h4><a id="resource_resolution">Resource Resolution</a></h4>
 537 
 538 <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>
 539 
 540 <pre class="code">
 541 &lt;Label text="%myText"/&gt;
 542 </pre>
 543 
 544 <p>If the loader is given a resource bundle defined as follows:</p>
 545 
 546 <pre class="code">
 547 myText = This is the text!
 548 </pre>
 549 
 550 
 551 <p>the output of the FXML loader would be a <span class="code">Label</span> instance containing the text "This is the text!".</p>
 552 
 553 <h4><a id="variable_resolution">Variable Resolution</a></h4>
 554 <p>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, as shown below:</p>
 555 
 556 <pre class="code">
 557 &lt;fx:define&gt;
 558     &lt;ToggleGroup fx:id="myToggleGroup"/&gt;
 559 &lt;/fx:define&gt;
 560 ...
 561 &lt;RadioButton text="A" toggleGroup="$myToggleGroup"/&gt;
 562 &lt;RadioButton text="B" toggleGroup="$myToggleGroup"/&gt;
 563 &lt;RadioButton text="C" toggleGroup="$myToggleGroup"/&gt;
 564 </pre>
 565 
 566 <p>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.</p>
 567 
 568 <h4><a id="escape_sequences">Escape Sequences</a></h4>
 569 
 570 <p>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. For example, the following markup creates a <span class="code">Label</span> instance whose text reads "$10.00":</p>
 571 
 572 <pre class="code">
 573 &lt;Label text="\$10.00"/&gt;
 574 </pre>
 575 
 576 <h4><a id="expression_binding">Expression Binding</a></h4>
 577 <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>
 578 
 579 <p>An expression binding also begins with the variable resolution operator, but is followed by a set of curly braces which wrap the expression value. 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>
 580 
 581 <pre class="code">
 582 &lt;TextField fx:id="textField"/&gt;
 583 &lt;Label text="${textField.text}"/&gt;
 584 </pre>
 585 
 586 <p>As the user types in the text input, the label's text content will be automatically updated.</p>
 587 
 588 <p>More complex expression are also supported. A list of supported constants and operators follows:</p>
 589 
 590 <table>
 591  <caption>Constants and Operators Table</caption>
 592  <tr><th scope="col">Constant / Operator</th><th scope="col">Description</th></tr>
 593  <tr><th scope="row">"string"<br />'string'</th><td>A string constant</td></tr>
 594  <tr><th scope="row">true<br />false</th><td>A boolean constant</td></tr>
 595  <tr><th scope="row">null</th><td>A constant representing the null value</td></tr>
 596  <tr><th scope="row">50.0<br />3e5<br />42</th><td>A numerical constant</td></tr>
 597  <tr><th scope="row">- <br/>(unary operator)</th><td>Unary minus operator, applied on a number</td>
 598  <tr><th scope="row">! <br/>(unary operator)</th><td>Unary negation of a boolean</td></tr>
 599  <tr><th scope="row">+ - <br />
 600                         * /
 601                         %</th> <td>Numerical binary operators</td></tr>
 602  <tr><th scope="row">&amp;&amp; ||</th><td>Boolean binary operators</td></tr>
 603  <tr><th scope="row">&gt; &gt;= <br />
 604                    &lt; &lt;= <br />
 605                    == !=</th>
 606                    <td>Binary operators of comparison.<br/> Both arguments must be of type Comparable</td></tr>
 607 </table>
 608 
 609 <h3><a id="static_property_attributes">Static Properties</a></h3>
 610 <p>Attributes representing static properties are handled similarly to static property elements and use a similar syntax. For example, the earlier <span class="code">GridPane</span> markup shown earlier to demonstrate static property elements could be rewritten as follows:</p>
 611 
 612 <pre class="code">
 613 &lt;GridPane&gt;
 614     &lt;children&gt;
 615         &lt;Label text="My Label" GridPane.rowIndex="0" GridPane.columnIndex="0"/&gt;
 616     &lt;/children&gt;
 617 &lt;/TabPane&gt;
 618 </pre>
 619 
 620 <p>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.</p>
 621 
 622 <h3><a id="event_handler_attributes">Event Handlers</a></h3>
 623 <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>
 624 
 625 <p>FXML supports three types of event handler attributes: script event handlers, controller method event handlers and expressions. Each are discussed below.</p>
 626 
 627 <h4><a id="script_event_handlers">Script Event Handlers</a></h4>
 628 <p>A script event handler is an event handler that executes script code when the event is fired, similar to event handlers in HTML. 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>
 629 
 630 <pre class="code">
 631 &lt;?language javascript?&gt;
 632 ...
 633 
 634 &lt;VBox&gt;
 635     &lt;children&gt;
 636         &lt;Button text="Click Me!"
 637             onAction="java.lang.System.out.println('You clicked me!');"/&gt;
 638     &lt;/children&gt;
 639 &lt;/VBox&gt;
 640 </pre>
 641 
 642 <p>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. Scripting is discussed in more detail in the next section.</p>
 643 
 644 <h4><a id="controller_method_event_handlers">Controller Method Event Handlers</a></h4>
 645 <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>
 646 
 647 <p>A controller method event handler is specified by a leading hash symbol followed by the name of the handler method. For example:</p>
 648 
 649 <pre class="code">
 650 &lt;VBox fx:controller="com.foo.MyController"
 651     xmlns:fx="http://javafx.com/fxml"&gt;
 652     &lt;children&gt;
 653         &lt;Button text="Click Me!" onAction="#handleButtonAction"/&gt;
 654     &lt;/children&gt;
 655 &lt;/VBox&gt;
 656 </pre>
 657 
 658 <p>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. If <span class="code">MyController</span> is defined as follows:</p>
 659 
 660 <pre class="code">
 661 package com.foo;
 662 
 663 public class MyController {
 664     public void handleButtonAction(ActionEvent event) {
 665         System.out.println("You clicked me!");
 666     }
 667 }
 668 </pre>
 669 
 670 <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>
 671 
 672 <p>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; however, it is optional and may be omitted if desired.
 673 So this is also a valid handler:</p>
 674 
 675 <pre class="code">
 676 package com.foo;
 677 
 678 public class MyController {
 679     public void handleButtonAction() {
 680         System.out.println("You clicked me!");
 681     }
 682 }
 683 </pre>
 684 
 685 <p>Controllers are discussed in more detail in a later section.</p>
 686 
 687 <h4><a id="expression_handlers">Event handlers from expressions</a></h4>
 688 <p>Any expression that point to a <a href="#variable_resolution">variable</a> of javafx.event.EventHandler type
 689     can be used as an expression handler. </p>
 690 <p>
 691 Previous example using an expression handler:
 692 </p>
 693 <pre class="code">
 694 &lt;VBox fx:controller="com.foo.MyController"
 695     xmlns:fx="http://javafx.com/fxml"&gt;
 696     &lt;children&gt;
 697         &lt;Button text="Click Me!" onAction="$controller.onActionHandler"/&gt;
 698     &lt;/children&gt;
 699 &lt;/VBox&gt;
 700 </pre>
 701 
 702 <p> With the controller that contains a field like this </p>
 703     
 704 <pre class="code">
 705 public class MyController {
 706     
 707     @FXML
 708     public EventHandler&lt;ActionEvent&gt; onActionHandler = new EventHandler&lt;&gt;() { ... }
 709 
 710     ...
 711 }  
 712 </pre>
 713 
 714 <p> Note that other kinds of expressions, like <a href="#expression_binding">binding expressions</a>
 715     are not supported in this context. </p>
 716 
 717 <h4><a id="collections_and_property_handlers">Special handlers for collections and properties</a></h4>
 718 <p> Collections and object properties cannot be listen to using <span class="code">setOn<span class="variable">Event</span>()</span> methods.
 719     For these reason, special handler methods need to be used.
 720 <span class="code">ObservableList</span>, <span class="code">ObservableMap</span> or <span class="code">ObservableSet</span>
 721  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.
 722 </p>
 723 <pre class="code">
 724 &lt;VBox fx:controller="com.foo.MyController"
 725     xmlns:fx="http://javafx.com/fxml"&gt;
 726     &lt;children onChange="#handleChildrenChange"/&gt;
 727 &lt;/VBox&gt;
 728 </pre>
 729 
 730 where the handler method looks like this:
 731 
 732 <pre class="code">
 733 package com.foo;
 734 
 735 import javafx.collections.ListChangeListener.Change;
 736 
 737 public class MyController {
 738     public void handleChildrenChange(ListChangeListener.Change c) {
 739         System.out.println("Children changed!");
 740     }
 741 }
 742 </pre>
 743 
 744 <p>Similarly, the property handlers are methods that have the same parameters as changed method of ChangeListener :</p>
 745 <p><span class="code">changed(ObservableValue&lt;? extends T&gt; observable, T oldValue, T newValue)</span></p>
 746 
 747 <p>A handler for parent property would look like this</p>
 748 <pre class="code">
 749 public class MyController {
 750     public void handleParentChange(ObservableValue value, Parent oldValue, Parent newValue) {
 751         System.out.println("Parent changed!");
 752     }
 753 }
 754 </pre>
 755 
 756 <p>For convenience, the first parameter can be a subclass of <span class="code">ObservableValue</span>,
 757     e.g. <span class="code">Property</span></p>
 758 
 759 <p>For registering to a property, a special <span class="code">on&lt;propertyName&gt;Change</span>
 760 attribute must be used.</p>
 761 
 762 <pre class="code">
 763 &lt;VBox fx:controller="com.foo.MyController"
 764     xmlns:fx="http://javafx.com/fxml" onParentChange="#handleParentChange"/&gt;
 765 </pre>
 766     
 767 <p>Note that collections and properties do not currently support scripting handlers.</p>
 768 
 769 <h2><a id="scripting">Scripting</a></h2>
 770 <p>
 771 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.</p>
 772 
 773 <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>
 774 
 775 <pre class="code">
 776 &lt;?language javascript?&gt;
 777 
 778 &lt;?import javafx.scene.control.*?&gt;
 779 &lt;?import javafx.scene.layout.*?&gt;
 780 
 781 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 782     &lt;fx:script&gt;
 783 
 784     function handleButtonAction(event) {
 785        java.lang.System.out.println('You clicked me!');
 786     }
 787     &lt;/fx:script&gt;
 788 
 789     &lt;children&gt;
 790         &lt;Button text="Click Me!" onAction="handleButtonAction(event);"/&gt;
 791     &lt;/children&gt;
 792 &lt;/VBox&gt;
 793 </pre>
 794 
 795 <p>Clicking the button triggers the event handler, which invokes the function, producing output identical to the previous examples.</p>
 796 
 797 <p>Script code may also be defined in external files. The previous example could be split into an FXML file and a JavaScript source file with no difference in functionality:</p>
 798 
 799 <div class="caption">example.fxml</div>
 800 <pre class="code">
 801 &lt;?import javafx.scene.control.*?&gt;
 802 &lt;?import javafx.scene.layout.*?&gt;
 803 
 804 &lt;VBox xmlns:fx="http://javafx.com/fxml"&gt;
 805     &lt;fx:script source="example.js" charset="cp1252"/&gt;
 806 
 807     &lt;children&gt;
 808         &lt;Button text="Click Me!" onAction="handleButtonAction(event);"/&gt;
 809     &lt;/children&gt;
 810 &lt;/VBox&gt;
 811 </pre>
 812 
 813 <div class="caption">example.js</div>
 814 <pre class="code">
 815 
 816 function handleButtonAction(event) {
 817    java.lang.System.out.println('You clicked me!');
 818 }
 819 </pre>
 820 
 821 <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>
 822 
 823 
 824 <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>
 825 
 826 <pre class="code">
 827 &lt;fx:script&gt;
 828 var myText = "This is the text of my label.";
 829 &lt;/fx:script&gt;
 830 
 831 ...
 832 
 833 &lt;Label text="$myText"/&gt;
 834 </pre>
 835 
 836 
 837 <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>
 838 
 839 <pre class="code">
 840 load("nashorn:mozilla_compat.js");
 841 importClass(java.lang.System);
 842 
 843 function handleButtonAction(event) {
 844    System.out.println('You clicked me!');
 845 }
 846 </pre> 
 847 
 848 <h2><a id="controllers">Controllers</a></h2>
 849 <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>
 850 
 851 <p>As shown earlier, controllers are often used to implement event handlers for user interface elements defined in markup:</p>
 852 
 853 <pre class="code">
 854 &lt;VBox fx:controller="com.foo.MyController"
 855     xmlns:fx="http://javafx.com/fxml"&gt;
 856     &lt;children&gt;
 857         &lt;Button text="Click Me!" onAction="#handleButtonAction"/&gt;
 858     &lt;/children&gt;
 859 &lt;/VBox&gt;
 860 </pre>
 861 
 862 <pre class="code">
 863 package com.foo;
 864 
 865 public class MyController {
 866     public void handleButtonAction(ActionEvent event) {
 867         System.out.println("You clicked me!");
 868     }
 869 }
 870 </pre>
 871 
 872 <p>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:</p>
 873 
 874 <pre class="code">
 875 public void initialize();
 876 </pre>
 877 
 878 <p>This allows the implementing class to perform any necessary post-processing on the content. 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>
 879 
 880 <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>
 881 
 882 <pre class="code">
 883 &lt;VBox fx:controller="com.foo.MyController"
 884     xmlns:fx="http://javafx.com/fxml"&gt;
 885     &lt;children&gt;
 886         &lt;Button fx:id="button" text="Click Me!"/&gt;
 887     &lt;/children&gt;
 888 &lt;/VBox&gt;
 889 </pre>
 890 
 891 <pre class="code">
 892 package com.foo;
 893 
 894 public class MyController implements Initializable {
 895     public Button button;
 896 
 897     @Override
 898     public void initialize(URL location, Resources resources)
 899         button.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
 900             @Override
 901             public void handle(ActionEvent event) {
 902                 System.out.println("You clicked me!");
 903             }
 904         });
 905     }
 906 }
 907 </pre>
 908 
 909 <h3><a id="fxml_annotation">@FXML</a></h3>
 910 <p>Note
 911 that, in the previous examples, the controller member fields and
 912 event handler methods were declared as public so they can be set
 913 or invoked by the loader. In practice, this is not often
 914 an issue, since a controller is generally only visible to the FXML
 915 loader that creates it.
 916 However, for developers who prefer more restricted
 917 visibility for controller fields or handler methods, the <span
 918 class="code">javafx.fxml.FXML</span> annotation can be used. This
 919 annotation marks a protected or private class member as accessible
 920 to FXML.
 921 If the class being annotated is in a named module, the
 922 module containing that class must <span class="code">open</span>
 923 the containing package to at least
 924 the <span class="code">javafx.fxml</span> module.</p>
 925 
 926 <p>For example, the controllers from the previous examples could be rewritten as follows:</p>
 927 
 928 <pre class="code">
 929 package com.foo;
 930 
 931 public class MyController {
 932     @FXML
 933     private void handleButtonAction(ActionEvent event) {
 934         System.out.println("You clicked me!");
 935     }
 936 }
 937 </pre>
 938 
 939 <pre class="code">
 940 package com.foo;
 941 
 942 public class MyController implements Initializable {
 943     @FXML private Button button;
 944 
 945     @FXML
 946     protected void initialize()
 947         button.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
 948             @Override
 949             public void handle(ActionEvent event) {
 950                 System.out.println("You clicked me!");
 951             }
 952         });
 953     }
 954 }
 955 </pre>
 956 
 957 <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>
 958 
 959 <h3><a id="nested_controllers">Nested Controllers</a></h3>
 960 <p>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. 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:
 961 
 962 <div class="caption">main_window_content.fxml</div>
 963 <pre class="code">
 964 &lt;VBox fx:controller="com.foo.MainController"&gt;
 965    &lt;fx:define&gt;
 966       &lt;fx:include fx:id="dialog" source="dialog.fxml"/&gt;
 967    &lt;/fx:define&gt;
 968    ...
 969 &lt;/VBox&gt;
 970 </pre>
 971 
 972 <div class="caption">MainController.java</div>
 973 <pre class="code">
 974 public class MainController extends Controller {
 975     @FXML private Window dialog;
 976     @FXML private DialogController dialogController;
 977 
 978     ...
 979 }
 980 </pre>
 981 
 982 <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>
 983 
 984 <h2><a id="fxmlloader">FXMLLoader</a></h2>
 985 <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>
 986 
 987 <pre class="code">
 988 URL location = getClass().getResource("example.fxml");
 989 ResourceBundle resources = ResourceBundle.getBundle("com.foo.example");
 990 FXMLLoader fxmlLoader = new FXMLLoader(location, resources);
 991 
 992 Pane root = (Pane)fxmlLoader.load();
 993 MyController controller = (MyController)fxmlLoader.getController();
 994 </pre>
 995 
 996 <p>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. 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>
 997 
 998 <h3><a id="custom_components">Custom Components</a></h3>
 999 <p>The <span class="code">setRoot()</span> and <span class="code">setController()</span> 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>
1000 
1001 <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>
1002 
1003 <pre class="code">
1004 &lt;?import javafx.scene.*?&gt;
1005 &lt;?import javafx.scene.control.*?&gt;
1006 &lt;?import javafx.scene.layout.*?&gt;
1007 
1008 &lt;fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml"&gt;
1009     &lt;TextField fx:id="textField"/&gt;
1010     &lt;Button text="Click Me" onAction="#doSomething"/&gt;
1011 &lt;/fx:root&gt;
1012 </pre>
1013 
1014 <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>. Prior to calling <span class="code">load()</span>, the caller must specify this value via a call to <span class="code">setRoot()</span>. 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. These two methods are commonly used together when creating custom FXML-based components.</p>
1015 
1016 <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>
1017 
1018 <pre class="code">
1019 package fxml;
1020 
1021 import java.io.IOException;
1022 
1023 import javafx.beans.property.StringProperty;
1024 import javafx.fxml.FXML;
1025 import javafx.fxml.FXMLLoader;
1026 import javafx.scene.control.TextField;
1027 import javafx.scene.layout.VBox;
1028 
1029 public class CustomControl extends VBox {
1030     @FXML private TextField textField;
1031 
1032     public CustomControl() {
1033         FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("custom_control.fxml"));
1034         fxmlLoader.setRoot(this);
1035         fxmlLoader.setController(this);
1036 
1037         try {
1038             fxmlLoader.load();
1039         } catch (IOException exception) {
1040             throw new RuntimeException(exception);
1041         }
1042     }
1043 
1044     public String getText() {
1045         return textProperty().get();
1046     }
1047 
1048     public void setText(String value) {
1049         textProperty().set(value);
1050     }
1051 
1052     public StringProperty textProperty() {
1053         return textField.textProperty();
1054     }
1055 
1056     @FXML
1057     protected void doSomething() {
1058         System.out.println("The button was clicked!");
1059     }
1060 }
1061 </pre>
1062 
1063 <p>Now, callers can use instances of this control in code or in markup, just like any other control; e.g.:</p>
1064 
1065 <div class="caption">Java</div>
1066 <pre class="code">
1067 HBox hbox = new HBox();
1068 CustomControl customControl = new CustomControl();
1069 customControl.setText("Hello World!");
1070 hbox.getChildren().add(customControl);
1071 </pre>
1072 
1073 <div class="caption">FXML</div>
1074 <pre class="code">
1075 &lt;HBox&gt;
1076     &lt;CustomControl text="Hello World!"/&gt;
1077 &lt;/HBox&gt;
1078 </pre>
1079 
1080 <h2><a id="deploy_as_module">Deploying an Application as a Module</a></h2>
1081 <p>If <span class="code">FXMLLoader</span> is used to load types in a named
1082 module, the application must ensure that all types that are referenced in the
1083 FXML files, including the controller class and any custom <span class="code">Node</span>
1084 classes, are reflectively accessible to the <span class="code">javafx.fxml</span>
1085 module. A type is reflectively accessible if the module
1086 <span class="code">opens</span> the containing package to at least the
1087 <span class="code">javafx.fxml</span> module.
1088 </p>
1089 
1090 <p>For example, if <span class="code">com.foo.MyController</span> is in the
1091 <span class="code">foo.app</span> module, the
1092 <span class="code">module-info.java</span> might look like this:
1093 </p>
1094 <pre><span class="code">module foo.app {
1095     opens com.foo to javafx.fxml;
1096 }</span></pre>
1097 
1098 <p>Alternatively, a type is reflectively accessible if the module
1099 <span class="code">exports</span> the containing package unconditionally.
1100 </p>
1101 <hr>
1102 <p>
1103 <small><a href="http://bugreport.java.com/bugreport/">Report a bug or suggest an enhancement</a><br> Copyright &copy; 2008, 2018, Oracle and/or its affiliates. All rights reserved.</small>
1104 </p>
1105 </body>
1106 </html>