0% found this document useful (0 votes)
9 views

JavaFxFXML Tutorial

This document summarizes an article about using FXML for creating JavaFX GUIs. It discusses key aspects of FXML like adding UI elements, importing Java types, setting properties, assigning identifiers, and using the corresponding Java class. It provides code examples to demonstrate how to structure FXML documents and link them to Java code to populate the GUI. The full article contains 9 sections that cover various FXML features in detail with additional code samples.

Uploaded by

luis larios
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JavaFxFXML Tutorial

This document summarizes an article about using FXML for creating JavaFX GUIs. It discusses key aspects of FXML like adding UI elements, importing Java types, setting properties, assigning identifiers, and using the corresponding Java class. It provides code examples to demonstrate how to structure FXML documents and link them to Java code to populate the GUI. The full article contains 9 sections that cover various FXML features in detail with additional code samples.

Uploaded by

luis larios
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

About Andreas Pomarolli

Andreas has graduated from Computer Science and Bioinformatics at the University of Linz. During his studies he
has been involved with a large number of research projects ranging from software engineering to data engineering
and at least web engineering. His scientific focus includes the areas of software engineering, data engineering, web
engineering and project management. He currently works as a software engineer in the IT sector where he is mainly
involved with projects based on Java, Databases and Web Technologies.
 
JavaFX FXML Tutorial
Posted by: Andreas Pomarolli in FXML April 14th, 2016 1 Comment 2064 Views

This is a JavaFX FXML Tutorial. In this tutorial we will discuss how to use FXML for
creating the GUI of an application. The first three chapters are also part of the
article JavaFX FXML Controller Example. Given the fact, that this article represents a
tutorial, it contains also the Controller Example.
FXML is an XML-based language designed to build the user interface for JavaFX
applications. You can use FXML to build an entire Scene or part of a  Scene . FXML allows
application developers to separate the logic for building the UI from the business logic. If
the UI part of the application changes, you do not need to recompile the JavaFX code.
Instead you can change the FXML using a text editor and rerun the application. You still
use JavaFX to write business logic using the Java language. An FXML document is an
XML document.
A JavaFX scene graph is a hierarchical structure of Java objects. XML format is well suited
for storing information representing some kind of hierarchy. Therefore, using FXML to
store the scene-graph is very intuitive. It is common to use FXML to build a scene graph in
a JavaFX application.
Want to master JavaFX?
Subscribe to our newsletter and download the JavaFX
Programming Cookbook right now!
In order to get you prepared for your JavaFX development needs, we have compiled numerous
recipes to help you kick-start your projects. Besides reading them online you may download
the eBook in PDF format!
 
Email address:
Sign up

The following table shows an overview of the whole article:

Table Of Contents
1. Introduction to FXML
1.1 The FXML Code
1.2 Adding UI Elements
1.3 Importing Java Types in FXML
1.4 Setting Properties in FXML
1.5 Specifying FXML Namespace
1.6 Assigning an Identifier to an Object
1.7 The Corresponding Java Class
1.8 The GUI
2. Using Script Event Handlers
2.1 The FXML Code
2.2 The Corresponding Java Class
2.3 The GUI
3. Using Controller Event Handlers
3.1 The FXML Code
3.2 The Controller Class
3.3 The Corresponding Java Class
3.4 The GUI
4. Including FXML Files
4.1 The FXML Code
4.2 The Corresponding Java Class
4.3 The GUI
5. Reusable Objects and Referencing Another Element
5.1 The FXML Code
5.2 Creating Reusable Objects in FXML
5.3 Referencing Another Element
5.4 The Corresponding Java Class
5.5 The GUI
6. Using Constants
6.1 The FXML Code
6.2 The Corresponding Java Class
6.3 The GUI
7. Binding Properties
7.1 The FXML Code
7.2 The Corresponding Java Class
7.3 The GUI
8. Using Resource Bundles
8.1 The FXML Code
8.2 The Properties Files for the Resource Bundles
8.2 The Corresponding Java Class
8.3 The GUI
9. Download Java Source Code

The following examples uses Java SE 8.


1. Introduction to FXML
1.1 The FXML Code
FxFXMLExample1.fxml
0 <?xml version="1.0" encoding="UTF-8"?>
1 <?language JavaScript?>
0  <?import javafx.scene.control.*?>
2 <?import javafx.scene.layout.*?>
0  
3
0
4
0
5
0
6
0
7
0
8
0
9
1
0 <VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" spa
  <style>
1
    -fx-padding: 10;
1     -fx-border-style: solid inside;
1     -fx-border-width: 2;
2     -fx-border-insets: 5;
1     -fx-border-radius: 5;
    -fx-border-color: blue;
3   </style>
1   <children>
4     <Label fx:id="inputLbl" alignment="CENTER_LEFT" cache="true" cacheHint="SCALE" prefHe
1     <TextField fx:id="inputText" prefWidth="100.0" />
5     <Button fx:id="okBtn" alignment="CENTER_RIGHT" contentDisplay="CENTER" mnemonicParsi
    <Label fx:id="outputLbl" alignment="CENTER_LEFT" cache="true" cacheHint="SCALE" prefH
1     <TextArea fx:id="outputText" prefHeight="100.0" prefWidth="200.0" wrapText="true" />
6   </children>
1 </VBox>
7
1
8
1
9
2
0
2
1
2
2
2
3
1.2 Adding UI Elements
The root element of the FXML document is the top-level object in the object-graph. The
top-level object of the above example is a VBox. Therefore, the root element of your
FXML would be:
1 <VBox>
2 </VBox>
How do you know that to represent a  VBox  in the object-graph, you need to use a tag in
FXML? It is both difficult and easy. It is difficult because there is no documentation for
FXML tags. It is easy because FXML has a few rules explaining what constitutes a tag
name. For example, if a tag name is the simple or fullqualified name of a class, the tag will
create an object of that class. The above element will create an object of the  VBox  class.
The above FXML can be rewritten using the fully qualified class name:
1 <javafx.scene.layout.VBox>
2 </javafx.scene.layout.VBox>
In JavaFX, layout panes have children. In FXML, layout panes have children as their child
elements. You can add a Label and a Button and other elements to the  VBox  as follows:
1 <children>
2     <Label/>
3     <TextField/>
4     <Button/>
5     <Label/>
    <TextArea/>
6 </children>
7
This defines the basic structure of the object-graph for our application. It will create
a  VBox  with two labels, a TextField, a TextArea and a  Button .
1.3 Importing Java Types in FXML
To use the simple names of Java classes in FXML, you must import the classes as you do in
Java programs. There is one exception. In Java programs, you do not need to import classes
from the  java.lang package . However, in FXML, you need to import classes from all
packages, including the  java.lang package . An import processing instruction is used to
import a class or all classes from a package. The following processing instructions import
the  VBox ,  Label , and  Button  classes:
1 <?import javafx.scene.layout.VBox?>
2 <?import javafx.scene.control.Label?>
3 <?import javafx.scene.control.Button?>
The following import processing instructions import all classes from
the  javafx.scene.control  and  java.lang  packages:
1 <?import javafx.scene.control.*?>
2 <?import java.lang.*?>

1.4 Setting Properties in FXML


You can set properties for Java objects in FXML. A property for an object can be set in
FXML if the property declaration follows the JavaBean conventions. The attribute name or
the property element name is the same as the name of the property being set. The following
FXML creates a  TextField  and sets its  prefWidth  property using an attribute:
1 <TextField fx:id="inputText" prefWidth="100.0" />

1.5 Specifying FXML Namespace


FXML does not have an XML schema. It uses a namespace that needs to be specified using
the namespace prefix “fx”. For the most part, the FXML parser will figure out the tag
names such as tag names that are classes, properties of the classes, and so on. FXML uses
special elements and attribute names, which must be qualified with the “fx” namespace
prefix. Optionally, you can append the version of the FXML in the namespace URI. The
FXML parser will verify that it can parse the specified.
The following FXML declares the “fx” namespace prefix.
1 <VBox xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2">...</V

1.6 Assigning an Identifier to an Object


An object created in FXML can be referred to somewhere else in the same document. It is
common to get the reference of UI objects created in FXML inside the JavaFX code. You
can achieve this by first identifying the objects in FXML with an  fx:id  attribute. The
value of the  fx:id  attribute is the identifier for the object. If the object type has an id
property, the value will be also set for the property. Note that each Node in JavaFX has an
id property that can be used to refer to them in CSS. The following is an example of
specifying the  fx:id  attribute for a  Label .
1 <Label fx:id="inputLbl"/>

1.7 The Corresponding Java Class


FxFXMLExample1.java
01 import java.io.FileInputStream;
import java.io.IOException;
02
03  
import javafx.application.Application;
04 import javafx.fxml.FXMLLoader;
05 import javafx.scene.Scene;
06 import javafx.scene.layout.VBox;
07 import javafx.stage.Stage;
08  
public class FxFXMLExample1 extends Application
09 {
10     public static void main(String[] args)
11     {
12         Application.launch(args);
13     }
14      
    @Override
15     public void start(Stage stage) throws IOException
16     {
17         // Create the FXMLLoader
18         FXMLLoader loader = new FXMLLoader();
        // Path to the FXML File
19
        String fxmlDocPath = "Path-To-Your-FXML-Files/FxFXMLExample1.fxml";
20         FileInputStream fxmlStream = new FileInputStream(fxmlDocPath);
21  
22         // Create the Pane and all Details
23         VBox root = (VBox) loader.load(fxmlStream);
24  
25         // Create the Scene
        Scene scene = new Scene(root);
26         // Set the Scene to the Stage
27         stage.setScene(scene);
28         // Set the Title to the Stage
29         stage.setTitle("A simple FXML Example");
30         // Display the Stage
        stage.show();
31
32
33
34     }
35 }
36
37
38
An FXML document defines the view part (the GUI) of a JavaFX application. You need to
load the FXML document to get the object-graph it represents. Loading an FXML is
performed by an instance of the FXMLLoader class. The  FXMLLoader class provides several
constructors that let you specify the location, charset, resource bundle, and other elements
to be used for loading the document.  FXMLLoader  supports loading a FXML document
using an InputStream. The following snippet of code loads the same FXML document
using an  InputStream .
1 // Create the FXMLLoader
2 FXMLLoader loader = new FXMLLoader();
3 // Path to the FXML File
4 String fxmlDocPath = "Path-To-Your-FXML-Files/FxFXMLExample1.fxml";
FileInputStream fxmlStream = new FileInputStream(fxmlDocPath);
5
Internally, the  FXMLLoader  reads the document using streams, which may throw
an IOException. All versions of the  load() method in  FXMLLoader  class
throw  IOException . In your application, you will need to handle the exception.
The  FXMLLoader class contains several versions of the  load()  method. Some of them are
instance methods and some static methods. You need to create an  FXMLLoader  instance and
use the instance  load()  method, if you want to retrieve more information from the loader,
such as the controller reference, resource bundle, the location, charset, and root object.
1 // Create the Pane and all Details
2 VBox root = (VBox) loader.load(fxmlStream);
What do you do next after loading an FXML document? The loader returns a  VBox , which
is set as the root for the  Scene . The rest of the code is the same as you have been using
except for one difference in the declaration of the  start() method. The method declares
that it may throw an  IOException , which you had to add because you have called
the  load()  method of the  FXMLLoader  inside the method.
1
// Create the Scene
2 Scene scene = new Scene(root);
3 // Set the Scene to the Stage
4 stage.setScene(scene);
5 // Set the Title to the Stage
stage.setTitle("A simple FXML Example");
6 // Display the Stage
7 stage.show();
8
1.8 The GUI
The following mage shows the application after starting. But at this time, a click on the
OK-Button has no effect. The reason for this behaviour is the fact, that we have not defined
an EventHandler at this time.

A simple JavaFX FXML Example

2. Using Script Event Handlers


2.1 The FXML Code
FxFXMLExample2.fxml
0 <?xml version="1.0" encoding="UTF-8"?>
1 <?language JavaScript?>
0  
<?import javafx.scene.control.*?>
2 <?import javafx.scene.layout.*?>
0  
3 <VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" spa
0   <style>
4     -fx-padding: 10;
    -fx-border-style: solid inside;
0     -fx-border-width: 2;
5     -fx-border-insets: 5;
0     -fx-border-radius: 5;
6     -fx-border-color: blue;
0   </style>
  <children>
7     <Label fx:id="inputLbl" alignment="CENTER_LEFT" cache="true" cacheHint="SCALE" prefHe
0     <TextField fx:id="inputText" prefWidth="100.0" />
8     <Button fx:id="okBtn" alignment="CENTER_RIGHT" contentDisplay="CENTER" mnemonicParsi
0     <Label fx:id="outputLbl" alignment="CENTER_LEFT" cache="true" cacheHint="SCALE" prefH
9     <TextArea fx:id="outputText" prefHeight="100.0" prefWidth="200.0" wrapText="true" />
    <fx:script>
1         function printOutput()
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1         {
9             outputText.setText(inputText.getText());
        }
2     </fx:script>   
0   </children>
2 </VBox>
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
You can set event handlers for nodes in FXML. Setting an event handler is similar to
setting any other properties. In FXML, you can specify two types of event handlers:
 Script Event Handlers
 Controller Event Handlers
In this chapter we will discuss Script Event Handlers. The Controller Event Handlers will
be discussed in the following chapter.
The script event handler is used when the event handler is defined in a scripting language.
The value of the attribute is the script itself, such as a function call or one or more
statements. The following snippet of FXML sets the ActionEvent handler for a  Button  that
calls the  printOutput()  function defined using JavaScript.
1 <?language JavaScript?>
2
 
3 <fx:script>
4     function printOutput()
5     {
6         outputText.setText(inputText.getText());
    }
7 </fx:script>   
8
If you want to execute the function  printOutput()  when the  Button  is clicked, you can set
the event handler as:
1 <Button fx:id="okBtn" onAction="printOutput();" text="OK" textAlignment="CENTER" />

2.2 The Corresponding Java Class


FxFXMLExample2.java
01 import java.io.FileInputStream;
import java.io.IOException;
02
03  
import javafx.application.Application;
04 import javafx.fxml.FXMLLoader;
05 import javafx.scene.Scene;
06 import javafx.scene.layout.VBox;
07 import javafx.stage.Stage;
08  
public class FxFXMLExample2 extends Application
09 {
10     public static void main(String[] args)
11     {
12         Application.launch(args);
13     }
14      
    @Override
15     public void start(Stage stage) throws IOException
16     {
17         // Create the FXMLLoader
18         FXMLLoader loader = new FXMLLoader();
        // Path to the FXML File
19
        String fxmlDocPath = "Path-To-Your-FXML-Files/FxFXMLExample2.fxml";
20         FileInputStream fxmlStream = new FileInputStream(fxmlDocPath);
21  
22         // Create the Pane and all Details
23         VBox root = (VBox) loader.load(fxmlStream);
24  
25         // Create the Scene
        Scene scene = new Scene(root);
26         // Set the Scene to the Stage
27         stage.setScene(scene);
28         // Set the Title to the Stage
29         stage.setTitle("A FXML Example with a Script Event Handler");
30
31
32
        // Display the Stage
33
        stage.show();
34
         
35     }
36 }
37
38
39
2.3 The GUI
The following image shows the result of our program after inserting a Text in
the  TextField  and pressing the  Button  “OK”:

A JavaFX FXML Example with a JavaScript Event Handler

3. Using Controller Event Handlers


3.1 The FXML Code
FxFXMLExample3.fxml
0 <?xml version="1.0" encoding="UTF-8"?>
1  
0 <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
2
 
0 <VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" spa
3 fx:controller="FxFXMLController">
0   <style>
4     -fx-padding: 10;
    -fx-border-style: solid inside;
0
5
0
6
0
7
0
8
0
9
1
0
1
1     -fx-border-width: 2;
1     -fx-border-insets: 5;
2     -fx-border-radius:
    -fx-border-color: blue;
5;
1   </style>
3   <children>
1     <Label fx:id="inputLbl" alignment="CENTER_LEFT" cache="true" cacheHint="SCALE" prefHe
4     <TextField fx:id="inputText" prefWidth="100.0" />
    <Button fx:id="okBtn" alignment="CENTER_RIGHT" contentDisplay="CENTER" mnemonicParsi
1     <Label fx:id="outputLbl" alignment="CENTER_LEFT" cache="true" cacheHint="SCALE" prefH
5     <TextArea fx:id="outputText" prefHeight="100.0" prefWidth="200.0" wrapText="true" />
1   </children>
6 </VBox>
1
7
1
8
1
9
2
0
2
1
2
2
A controller is simply a class name whose object is created by FXML and used to initialize
the UI elements. FXML lets you specify a controller on the root element using
the  fx:controller  attribute. Note that only one controller is allowed per FXML document,
and if specified, it must be specified on the root element. The following FXML specifies a
controller for the  VBox element.
1 <VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx
A controller needs to conform to some rules and it can be used for different reasons:
 The controller is instantiated by the FXML loader.
 The controller must have a public no-args constructor. If it does not exist, the FXML
loader will not be able to instantiate it, which will throw an exception at the load time.
 The controller can have accessible methods, which can be specified as event handlers in
FXML.
 The FXML loader will automatically look for accessible instance variables of the
controller. If the name of an accessible instance variable matches the fx:id attribute of an
element, the object reference from FXML is automatically copied into the controller
instance variable. This feature makes the references of UI elements in FXML available
to the controller. The controller can use them later, such as binding them to model.
 The controller can have an accessible initialize() method, which should take no
arguments and have a return type of void. The FXML loader will call the initialize()
method after the loading of the FXML document is complete.
3.2 The Controller Class
FxFXMLController.java
01 import java.net.URL;
import java.util.ResourceBundle;
02
03  
import javafx.fxml.FXML;
04 import javafx.scene.control.TextArea;
05 import javafx.scene.control.TextField;
06  
07 public class FxFXMLController
08 {
    @FXML
09     // The reference of inputText will be injected by the FXML loader
10     private TextField inputText;
11      
12     // The reference of outputText will be injected by the FXML loader
13     @FXML
14     private TextArea outputText;
15      
    // location and resources will be automatically injected by the FXML loader
16     @FXML
17     private URL location;
18      
19     @FXML
20     private ResourceBundle resources;
21      
22     // Add a public no-args constructor
    public FxFXMLController()
23     {
24     }
25      
26     @FXML
27     private void initialize()
28     {
    }
29
     
30     @FXML
31     private void printOutput()
32     {
33         outputText.setText(inputText.getText());
    }
34
35
36
37 }
38
39
40
The controller class uses a  @FXML  annotation on some members. The  @FXML  annotation can
be used on fields and methods. It cannot be used on classes and constructors. By using
a  @FXML  annotation on a member, you are declaring that the FXML loader can access the
member even if it is private. A public member used by the FXML loader does not need to
be annotated with  @FXML . However, annotating a public member with  @FXML  is not an error.
It is better to annotate all members, public and private, used by the FXML loader with
the  @FXML  annotation. This tells the reader of your code how the members are being used.
The following FXML sets the  printOutput()  method of the controller class as the event
handler for the  Button :
<VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" spac
1fx:controller="FXFXML.FxFXMLController">

3<Button fx:id="okBtn" alignment="CENTER_RIGHT" contentDisplay="CENTER" mnemonicParsing="f
There are two special instance variables that can be declared in the controller and they are
automatically injected by the FXML loader:
 @FXML private URL location;
 @FXML private ResourceBundle resources;
The location is the location of the FXML document. The resources is the reference of
the ResourceBundle. When the event handler attribute value starts with a hash symbol (#),
it indicates to the FXML loader that  printOutput()  is the method in the controller, not in a
script.
The event handler method in the controller should conform to some rules:
 The method may take no arguments or a single argument. If it takes an argument, the
argument type must be a type assignment compatible with the event it is supposed to
handle.
 Conventionally, the method return type should be void, because there is no taker of the
returned value.
 The method must be accessible to the FXML loader: make it public or annotate it with
@FXML.
 When the FXML loader is done loading the FXML document, it calls the initialize()
method of the controller. The method should not take any argument. It should be
accessible to the FXML loader. In the controller, you used the @FXML annotation to
make it accessible to the FXML loader.
3.3 The Corresponding Java Class
FxFXMLExample3.java
01 import java.io.FileInputStream;
import java.io.IOException;
02
03
04
05
06  
import javafx.application.Application;
07 import javafx.fxml.FXMLLoader;
08 import javafx.scene.Scene;
09 import javafx.scene.layout.VBox;
10 import javafx.stage.Stage;
11  
public class FxFXMLExample3 extends Application
12
{
13     public static void main(String[] args)
14     {
15         Application.launch(args);
16     }
17      
    @Override
18     public void start(Stage stage) throws IOException
19     {
20         // Create the FXMLLoader
21         FXMLLoader loader = new FXMLLoader();
22         // Path to the FXML File
        String fxmlDocPath = "Path-To-Your-FXML-Files/FxFXMLExample3.fxml";
23         FileInputStream fxmlStream = new FileInputStream(fxmlDocPath);
24  
25         // Create the Pane and all Details
26         VBox root = (VBox) loader.load(fxmlStream);
27  
28         // Create the Scene
        Scene scene = new Scene(root);
29
        // Set the Scene to the Stage
30         stage.setScene(scene);
31         // Set the Title to the Stage
32         stage.setTitle("A FXML Example with a Controller");
33         // Display the Stage
        stage.show();
34
         
35     }
36 }
37
38
39
3.4 The GUI
The following image shows the result of our program:
A JavaFX FXML Controller Example

4. Including FXML Files


4.1 The FXML Code
In this example the FXML Code is divided into three FXML Files.
A separate FXML File for creating a  Label :
FxFXMLLabel.fxml
1 <?import javafx.scene.control.*?>
2 <?import java.lang.Integer?>
3  
4 <Label alignment="CENTER_LEFT" cache="true" cacheHint="SCALE" prefHeight="30.0" prefWid
A separate FXML File for creating a  Button :
FxFXMLButton.fxml
1 <?import javafx.scene.control.*?>
2  
3 <Button alignment="CENTER_RIGHT" contentDisplay="CENTER" mnemonicParsing="false" textA
And at least, the main FXML File:
FxFXMLExample4.fxml
0 <?xml version="1.0" encoding="UTF-8"?>
1  
0 <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
2
 
0 <VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" spa
3 fx:controller="FXFXML.FxFXMLController">
0   <style>
4     -fx-padding: 10;
    -fx-border-style: solid inside;
0     -fx-border-width: 2;
5     -fx-border-insets: 5;
0     -fx-border-radius: 5;
6
0
7
0
8
0
9
1
0
1
1
1
2     -fx-border-color: blue;
1   </style>
3   <children>
1     <fx:include source="/FXFXML/FxFXMLLabel.fxml" fx:id="inputLbl" text="Please insert Y
    <TextField fx:id="inputText" prefWidth="100.0" />
4     <fx:include source="/FXFXML/FxFXMLButton.fxml" fx:id="okBtn" text="OK" onAction="#pr
1     <fx:include source="/FXFXML/FxFXMLLabel.fxml" fx:id="outputLbl" text="Your Input:"/>
5     <TextArea fx:id="outputText" prefHeight="100.0" prefWidth="100.0" />
1   </children>
6 </VBox>
1
7
1
8
1
9
2
0
2
1
2
2
An FXML document can include another FXML document using
the  <fx:include>  element. The objectgraph generated by the nested document is included
at the position where the nested document occurs in the containing document.
The  <fx:include>  element takes a source attribute whose value is the path of the nested
document.
1 <fx:include source="/FXFXML/FxFXMLLabel.fxml" fx:id="inputLbl" text="Please insert You
If the nested document path starts with a leading forward slash, the path is resolved relative
to the CLASSPATH. Otherwise, it is resolved related to the containing document path.
The  <fx:include>  element can have the  fx:id  attribute and all attributes that are available
for the included object. The attributes specified in the containing document override the
corresponding attributes in the included document.
For example, if you include an FXML document, which creates a  Label , you can specify
the text property in the included document as well as the containing document. When the
containing document is loaded, the text property from the containing document will be
used.
1 <fx:include source="/FXFXML/FxFXMLLabel.fxml" fx:id="inputLbl" text="Please insert You
For example, if you include an FXML document, which creates a  Button , you can specify
the text property in the included document as well as the containing document. When the
containing document is loaded, the text property from the containing document will be
used.
1 <fx:include source="/FXFXML/FxFXMLButton.fxml" fx:id="okBtn" text="OK" onAction="#prin
An FXML document may optionally specify a controller using the fx:controller attribute for
the root element. The rule is that you can have maximum of one controller per FXML
document. When you nest documents, each document can have its own controller.
<VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" spac
1fx:controller="FXFXML.FxFXMLController">
4.2 The Corresponding Java Class
01 import java.io.FileInputStream;
import java.io.IOException;
02
03  
import javafx.application.Application;
04 import javafx.fxml.FXMLLoader;
05 import javafx.scene.Scene;
06 import javafx.scene.layout.VBox;
07 import javafx.stage.Stage;
08  
public class FxFXMLExample4 extends Application
09 {
10     public static void main(String[] args)
11     {
12         Application.launch(args);
13     }
14      
    @Override
15     public void start(Stage stage) throws IOException
16     {
17         // Create the FXMLLoader
18         FXMLLoader loader = new FXMLLoader();
        // Path to the FXML File
19
        String fxmlDocPath = "Path-To-Your-FXML-Files/FxFXMLExample4.fxml";
20         FileInputStream fxmlStream = new FileInputStream(fxmlDocPath);
21  
22         // Create the Pane and all Details
23         VBox root = (VBox) loader.load(fxmlStream);
24  
25         // Create the Scene
        Scene scene = new Scene(root);
26         // Set the Scene to the Stage
27         stage.setScene(scene);
28         // Set the Title to the Stage
29         stage.setTitle("A FXML Example which includes FXML Files");
30         // Display the Stage
        stage.show();
31     }
32 }
33
34
35
36
37
38
4.3 The GUI
The following image shows the GUI of the above example. It loads the
FxFXMLExample4.fxml and adds the loaded  VBox  to the  Scene . It displays a window with
the OK  Button  from the FxFXMLButton.fxml file and the labels are loaded from the
FxFXMLLabel.fxml file.

A JavaFX FXML Example with external FXML Files

5. Reusable Objects and Referencing


Another Element
5.1 The FXML Code
FxFXMLExample5.fxml
01 <?import javafx.scene.layout.VBox?>
02 <?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
03
 
04 <VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" sp
05     <fx:define>
06         <Image url="/FXFXML/JavaFx.jpg" fx:id="javaImg"/>
07     </fx:define>
    <children>
08         <fx:include source="/FXFXML/FxFXMLLabel.fxml" fx:id="javaLbl" text="The JavaFX
09         <ImageView fx:id="view">
10             <image>
                <fx:reference source="javaImg"/>
11
12
13             </image>
        </ImageView>
14     </children>
15 </VBox>
16
17
5.2 Creating Reusable Objects in FXML
Sometimes, you need to create objects that are not directly part of the object-graph.
However, they may be used somewhere else in the FXML document. You can create an
object in FXML without making it part of the object-group using the  <fx:define>  block.
You can refer to the objects created in the block by their  fx:id  in the attribute value of
other elements. The attribute value must be prefixed with a dollar symbol ($).
1 <fx:define>
2     <Image url="/FXFXML/JavaFx.jpg" fx:id="javaImg"/>
3 </fx:define>

5.3 Referencing Another Element


You can reference another element in the document using the  <fx:reference>  element.
The  fx:id  attribute specifies the  fx:id  of the referred element.  <fx:reference
source="fx:id of the source element"/>
The following FXML content uses an  <fx:reference>  element to refer to an Image.
1 <ImageView fx:id="view">
2     <image>
3         <fx:reference source="javaImg"/>
4     </image>
</ImageView>
5
5.4 The Corresponding Java Class
FxFXMLExample5.java
01 import java.io.FileInputStream;
import java.io.IOException;
02
03  
import javafx.application.Application;
04 import javafx.fxml.FXMLLoader;
05 import javafx.scene.Scene;
06 import javafx.scene.layout.VBox;
07 import javafx.stage.Stage;
08  
public class FxFXMLExample5 extends Application
09 {
10     public static void main(String[] args)
11     {
12         Application.launch(args);
13     }
14      
    @Override
15     public void start(Stage stage) throws IOException
16     {
17
18
19
20         // Create the FXMLLoader
        FXMLLoader loader = new FXMLLoader();
21
        // Path to the FXML File
22         String fxmlDocPath = "Path-To-Your-FXML-Files/FxFXMLExample5.fxml";
23         FileInputStream fxmlStream = new FileInputStream(fxmlDocPath);
24  
25         // Create the Pane and all Details
26         VBox root = (VBox) loader.load(fxmlStream);
27  
        // Create the Scene
28         Scene scene = new Scene(root);
29         // Set the Scene to the Stage
30         stage.setScene(scene);
31         // Set the Title to the Stage
32         stage.setTitle("A FXML Example with Reuseable Objects");
        // Display the Stage
33         stage.show();
34     }
35 }
36
37
38
5.5 The GUI
In the following GUI, you can see the effect of using a referenced element in FXML:

A JavaFX FXML Example with Reusable Objects


6. Using Constants
6.1 The FXML Code
FxFXMLExample6.fxml
0 <?xml version="1.0" encoding="UTF-8"?>
1 <?language JavaScript?>
0  <?import javafx.scene.control.*?>
2 <?import javafx.scene.layout.*?>
0 <?import javafx.geometry.Pos?>
3  
0 <VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" spa
4 fx:controller="FXFXML.FxFXMLController">
  <style>
0     -fx-padding: 10;
5     -fx-border-style: solid inside;
0     -fx-border-width: 2;
6     -fx-border-insets: 5;
0     -fx-border-radius: 5;
    -fx-border-color: blue;
7   </style>
0     <alignment><Pos fx:constant="CENTER" fx:id="alignCenter"/></alignment>
8   <children>
0     <Label fx:id="inputLbl" alignment="$alignCenter" cache="true" cacheHint="SCALE" prefH
9     <TextField fx:id="inputText" prefWidth="100.0" />
    <Button fx:id="okBtn" alignment="$alignCenter" mnemonicParsing="false" onAction="#pr
1     <Label fx:id="outputLbl" alignment="$alignCenter" cache="true" cacheHint="SCALE" pref
0     <TextArea fx:id="outputText" prefHeight="100.0" prefWidth="200.0" wrapText="true" />
1   </children>
1 </VBox>
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
Classes, interfaces, and enums may define constants, which are static, final variables. You
can refer to those constants using the  fx:constant  attribute. The attribute value is the name
of the constant. The name of the element is the name of the type that contains the constant.
Note that all enum constants belong to this category and they can be accessed using
the  fx:constant  attribute. The following element accesses the  Pos.CENTER  enum constant.
1 <alignment><Pos fx:constant="CENTER" fx:id="alignCenter"/></alignment>

6.2 The Corresponding Java Class


FxFXMLExample6.java
01 import java.io.FileInputStream;
import java.io.IOException;
02
03  
import javafx.application.Application;
04 import javafx.fxml.FXMLLoader;
05 import javafx.scene.Scene;
06 import javafx.scene.layout.VBox;
07 import javafx.stage.Stage;
08  
public class FxFXMLExample6 extends Application
09 {
10     public static void main(String[] args)
11     {
12         Application.launch(args);
13     }
14      
    @Override
15     public void start(Stage stage) throws IOException
16     {
17         // Create the FXMLLoader
18         FXMLLoader loader = new FXMLLoader();
        // Path to the FXML File
19
        String fxmlDocPath = "Path-To-Your-FXML-Files/FxFXMLExample6.fxml";
20         FileInputStream fxmlStream = new FileInputStream(fxmlDocPath);
21  
22         // Create the Pane and all Details
23         VBox root = (VBox) loader.load(fxmlStream);
24  
25         // Create the Scene
        Scene scene = new Scene(root);
26         // Set the Scene to the Stage
27         stage.setScene(scene);
28         // Set the Title to the Stage
29         stage.setTitle("A FXML Example with Constants");
30         // Display the Stage
31
32
33
        stage.show();
34     }
35 }
36
37
38
6.3 The GUI
The following GUI represents the effect of the usage of the constant  alignCenter :

A JavaFX FXML Example with Constants

7. Binding Properties
7.1 The FXML Code
FxFXMLExample7.fxml
01 <?xml version="1.0" encoding="UTF-8"?>
02  
03 <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
04
 
05 <VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" sp
06   <style>
07     -fx-padding: 10;
08     -fx-border-style: solid inside;
    -fx-border-width: 2;
09     -fx-border-insets: 5;
10     -fx-border-radius: 5;
11     -fx-border-color: blue;
12   </style>
13   <children>
    <fx:include source="/FXFXML/FxFXMLLabel.fxml" fx:id="inputLbl" text="Please insert
14
15
16     <TextField fx:id="inputText" prefWidth="100.0" />
17     <fx:include source="/FXFXML/FxFXMLLabel.fxml" fx:id="outputLbl" text="Your Input:"/
18     <TextArea fx:id="outputText" text="${inputText.text}" prefHeight="100.0" prefWidth=
19   </children>
</VBox>
20
21
FXML supports simple property bindings. You need to use an attribute for the property to
bind it to the property of another element or a document variable. The attribute value starts
with a $ symbol, which is followed with a pair of curly braces.
The following FXML content creates a VBox with two TextFields. The text property of the
outputText field is bound to the text property of the inputText field.
1 <TextArea fx:id="outputText" text="${inputText.text}" prefHeight="100.0" prefWidth="10

7.2 The Corresponding Java Class


FxFXMLExample7.java
01 import java.io.FileInputStream;
import java.io.IOException;
02
03  
import javafx.application.Application;
04 import javafx.fxml.FXMLLoader;
05 import javafx.scene.Scene;
06 import javafx.scene.layout.VBox;
07 import javafx.stage.Stage;
08  
public class FxFXMLExample7 extends Application
09 {
10     public static void main(String[] args)
11     {
12         Application.launch(args);
13     }
14  
    @Override
15     public void start(Stage stage) throws IOException
16     {
17         // Create the FXMLLoader
18         FXMLLoader loader = new FXMLLoader();
        // Path to the FXML File
19         String fxmlDocPath = "Path-To-Your-FXML-Files/FxFXMLExample7.fxml";
20         FileInputStream fxmlStream = new FileInputStream(fxmlDocPath);
21  
22         // Create the Pane and all Details
23         VBox root = (VBox) loader.load(fxmlStream);
24  
25         // Create the Scene
        Scene scene = new Scene(root);
26         // Set the Scene to the Stage
27         stage.setScene(scene);
28         // Set the Title to the Stage
29         stage.setTitle("A FXML Example with Binding Properties");
30         // Display the Stage
        stage.show();
31     }
32
33
34
35 }
36
37
38
7.3 The GUI
In the following GUI the text from the  TextField  will be direct copied to the  TextArea :

A JavaFX FXML Example with Binding Properties

8. Using Resource Bundles


8.1 The FXML Code
FxFXMLExample8.fxml
0 <?xml version="1.0" encoding="UTF-8"?>
1 <?language JavaScript?>
0  <?import javafx.scene.control.*?>
2 <?import javafx.scene.layout.*?>
0 <?import javafx.geometry.Pos?>
3  
0 <VBox fx:id="vbox" layoutX="10.0" layoutY="10.0" prefHeight="250.0" prefWidth="300.0" spa
4 fx:controller="FXFXML.FxFXMLController">
  <style>
0     -fx-padding: 10;
5     -fx-border-style: solid inside;
0     -fx-border-width: 2;
6     -fx-border-insets: 5;
0     -fx-border-radius: 5;
    -fx-border-color: blue;
7   </style>
0
8
0
9
1
0
1
1
1
2
1
3
1
4
1
5     <alignment><Pos
  <children>
fx:constant="CENTER_LEFT" fx:id="alignCenter"/></alignment>
1     <Label fx:id="inputLbl" alignment="$alignCenter" cache="true" cacheHint="SCALE" prefH
6     <TextField fx:id="inputText" prefWidth="100.0" />
1     <Button fx:id="okBtn" alignment="$alignCenter" mnemonicParsing="false" onAction="#pr
7     <Label fx:id="outputLbl" alignment="$alignCenter" cache="true" cacheHint="SCALE" pref
    <TextArea fx:id="outputText" prefHeight="100.0" prefWidth="200.0" wrapText="true" />
1   </children>
8 </VBox>
1
9
2
0
2
1
2
2
2
3
2
4
2
5
Using a  ResourceBundle  in FXML is much easier than using it in Java code. Specifying the
keys from a  ResourceBundle  in attribute values uses the corresponding values for the
default Locale. If an attribute value starts with a % symbol, it is considered as the key name
from the resource bundle.
At runtime, the attribute value will come from the specified  ResourceBundle  in
the  FXMLLoader . If you want to use a leading % symbol in an attribute value, escape it with
a backward slash (e.g., “\%key”).
Our example uses “%input” and “%output” as the value for the text property of the  Label .
The attribute value starts with a % symbol. The  FXMLLoader  will look up the value of the
“input” and “output” in the  ResourceBundle  and use it for the text property.
1 <Label fx:id="inputLbl" alignment="$alignCenter" cache="true" cacheHint="SCALE" prefHei
2 <Label fx:id="outputLbl" alignment="$alignCenter" cache="true" cacheHint="SCALE" prefHe

8.2 The Properties Files for the Resource Bundles


In our example, we are using three  ResourceBundle  files: one for default  Locale  named
Labels.properties, one for the German  Locale  named Labels_de.properties and one for the
English  Locale  named Labels_en.properties:
Labels.properties
1 input=Input:
2 output=Output:
Labels_de.properties
1 input=Bitte geben Sie her Ihren Text ein:
2 output=Ihre Eingabe:
Labels_en.properties
1 input=Please insert Your Input here:
2 output=Your Input:

8.2 The Corresponding Java Class


FxFXMLExample8.java
01 import java.io.IOException;
import java.util.Locale;
02
import java.util.ResourceBundle;
03
 
04 import javafx.application.Application;
05 import javafx.fxml.FXMLLoader;
06 import javafx.scene.Scene;
07 import javafx.scene.layout.VBox;
import javafx.stage.Stage;
08
09  
public class FxFXMLExample8 extends Application
10 {
11     public static void main(String[] args)
12     {
13         Application.launch(args);
    }
14
     
15     @Override
16     public void start(Stage stage) throws IOException
17     {
18         FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setResources(ResourceBundle.getBundle("FXFXML.Labels", new Locale
19
        VBox root = (VBox) fxmlLoader.load(this.getClass().getResource("FxFXMLExamp
20         // replace the content
21         // Create the Scene
22         Scene scene = new Scene(root);
23         // Set the Scene to the Stage
        stage.setScene(scene);
24         // Set the Title to the Stage
25         stage.setTitle("A FXML Example using Resource Bundles");
26         // Display the Stage
27         stage.show();
28     }
}
29
30
31
32
33
34
8.3 The GUI
The following GUI shows the effect of using a  ResourceBundle  for the German  Locale :

A JavaFX FXML Example with a ResourceBundle

9. Download Java Source Code


This was a JavaFX FXML Tutorial.
Download
You can download the full source code of this example here: JavaFxFXMLTutorial.zip

You might also like