Creating Custom JavaFX Components with Scene Builder and FXML.

One of the goals of our development with our JavaFX application is to try to keep as much as the UI design as possible within the Scene Builder UI design tool, and the business logic for the application in Java.  One of the things that is not entirely clear is how to create a new component in Scene Builder and then reuse that component within other components created in Scene Builder.

In the example below I illustrate how to create a custom table and ‘Add Plan’ components and then add them to a new Scene using FXML.

The first step is to create a simple component which which act as an “Add Plan” widget on the UI.  The widget contains an AnchorPane, ImageView and Label.

image

For the next step, open up the FXML file and change the first “AnchorPane” declaration to “<fx:root…” as in the example code below.  The type must be the same as the controller/root class which I will illustrate below.  In this case, the root/controller class will extend javafx.scene.layout.AnchorPane

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<fx:root type="javafx.scene.layout.AnchorPane" xmlns:fx="http://javafx.com/fxml">
  <children>
    <AnchorPane fx:id="myTestButton" layoutX="0.0" layoutY="5.0" minHeight="58.0" prefHeight="74.0" prefWidth="129.0244140625" styleClass="main-back">
      <children>
        <ImageView fitHeight="44.0" fitWidth="44.0" layoutX="43.0" layoutY="8.0" pickOnBounds="true" preserveRatio="true">
          <image>
            <Image url="@new-plan.png" preserveRatio="false" smooth="false" />
          </image>
        </ImageView>
        <Label layoutX="43.0" layoutY="52.0" text="Add Plan" textFill="WHITE">
          <font>
            <Font name="System Bold" size="12.0" />
          </font>
        </Label>
      </children>
      <effect>
        <DropShadow />
      </effect>
    </AnchorPane>
  </children>
  </fx:root>

Create a class which will act as both the root of the component as well as its controller.  The class must extend the type that was previously defined in the FXML file.  Use the FXML loader to set the root and controller of the component to “this” class, and then load the component’s FXML file.

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.lynden.fx.test; import com.lynden.ui.util.UIUtilities; import java.io.IOException; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.TransferMode; import javafx.scene.layout.AnchorPane;

 

/**

* * @author ROBT */ public class TestButton extends AnchorPane { @FXML private AnchorPane myTestButton; public TestButton() {    FXMLLoader fxmlLoader = new FXMLLoader(

getClass().getResource("/com/lynden/planning/ui/TestButton.fxml"));

 

 

fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException exception) { throw new RuntimeException(exception); } }

}

 

Next, the 2nd component is a TableView which contains a collection of beans, and displays their corresponding data.

image

As with the last component, the first <AnchorPane> declaration is changed to <fx:root>

<?xml version="1.0" encoding="UTF-8"?>

<?import com.lynden.fx.*?>
<?import com.lynden.fx.table.*?>
<?import com.lynden.fx.test.*?>
<?import com.lynden.planning.ui.*?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.text.*?>
<?import javafx.util.*?>
<?scenebuilder-classpath-element split-flip-1.0.0.jar?>

<fx:root type="javafx.scene.layout.AnchorPane" xmlns:fx="http://javafx.com/fxml">
  <children>
    <BorderPane layoutX="0.0" layoutY="0.0" prefHeight="400.0" prefWidth="600.0">
      <center>
        <TableView fx:id="myTableView" prefHeight="200.0" prefWidth="200.0">
          <columns>
            <TableColumn prefWidth="42.0" text="">
            </TableColumn>
            <TableColumn prefWidth="110.0" text="Plan">
              <cellValueFactory>
                <PropertyValueFactory property="vfcPlan" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="55.0" text="VFC #">
              <cellValueFactory>
                <PropertyValueFactory property="vfcNumber" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="100.0" text="Location">
              <cellValueFactory>
                <PropertyValueFactory property="location" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="100.0" text="Arrival">
              <cellValueFactory>
                <PropertyValueFactory property="arrivalTime" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="35.0" text="Org">
              <cellValueFactory>
                <PropertyValueFactory property="origin" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="35.0" text="Dst">
              <cellValueFactory>
                <PropertyValueFactory property="destination" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="65.0" text="Shipments">
              <cellValueFactory>
                <PropertyValueFactory property="shipments" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="125.0" text="Consignee">
              <cellValueFactory>
                <PropertyValueFactory property="consignee" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="35.0" text="Haz">
              <cellValueFactory>
                <PropertyValueFactory property="hazMat" />
              </cellValueFactory>
            </TableColumn>
            <TableColumn prefWidth="45.0" text="Temp">
              <cellValueFactory>
                <PropertyValueFactory property="temperature" />
              </cellValueFactory>
            </TableColumn>
          </columns>
          <items>
            <FXCollections fx:factory="observableArrayList">
              <InboundBean arrivalTime="03-11-13 15:00" consignee="FMeyer" destination="ANC" hazMat="N" location="Consignee" origin="TAC" shipments="1" temperature="KFF" vfcNumber="345440" vfcPlan="Fred Meyer" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="FMeyer" destination="ANC" hazMat="N" location="Yard" origin="TAC" shipments="1" temperature="KFF" vfcNumber="123456" vfcPlan="Fred Meyer" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="FMeyer" destination="ANC" hazMat="N" location="Trip 12543" origin="TAC" shipments="1" temperature="KFF" vfcNumber="235555" vfcPlan="Fred Meyer" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="Costco" destination="KNA" hazMat="N" location="Trip 551332" origin="TAC" recovered="false" shipments="1" temperature="KFF" vfcNumber="244000" vfcPlan="KNA" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="SBS" destination="ANC" hazMat="N" location="Trip 12543" origin="TAC" recovered="false" shipments="1" temperature="KFF" vfcNumber="291007" vfcPlan="Sealand" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="Costco" destination="FBK" hazMat="N" location="Yard" origin="TAC" recovered="true" shipments="2" temperature="KFF" vfcNumber="291008" vfcPlan="Fairbanks" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="" destination="KNA" hazMat="N" location="Trip 12543" origin="TAC" recovered="false" shipments="1" temperature="KFF" vfcNumber="234554" vfcPlan="" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="" destination="ANC" hazMat="N" location="2" origin="TAC" recovered="false" shipments="2" temperature="KFF" vfcNumber="123407" vfcPlan="Darigold" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="" destination="FBK" hazMat="N" location="Yard" origin="TAC" recovered="true" shipments="1" temperature="KFF" vfcNumber="233458" vfcPlan="Yard" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="" destination="KNA" hazMat="N" location="" origin="TAC" recovered="false" shipments="1" temperature="KFF" vfcNumber="244340" vfcPlan="Flat" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="" destination="ANC" hazMat="Y" location="Trip 12543" origin="TAC" recovered="false" shipments="2" temperature="KFF" vfcNumber="222347" vfcPlan="" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="" destination="FBK" hazMat="N" location="" origin="TAC" recovered="false" shipments="1" temperature="KFF" vfcNumber="312008" vfcPlan="" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="" destination="KNA" hazMat="N" location="Trip 551332" origin="TAC" recovered="false" shipments="1" temperature="KFF" vfcNumber="313000" vfcPlan="" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="SBS" destination="ANC" hazMat="N" location="" origin="TAC" recovered="false" shipments="2" temperature="KFF" vfcNumber="334507" vfcPlan="" />
              <InboundBean arrivalTime="03-11-13 15:00" consignee="" destination="FBK" hazMat="N" location="" origin="TAC" recovered="false" shipments="1" temperature="KFF" vfcNumber="244408" vfcPlan="" />
            </FXCollections>
          </items>
        </TableView>
      </center>
    </BorderPane>
  </children>
</fx:root>

 

Next, the corresponding root and controller class is created for the table component.

package com.lynden.fx.test;

import com.lynden.fx.InboundBean; 
import java.io.IOException;
import javafx.event.EventHandler;
import javafx.event.EventType; 
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader; 
import javafx.scene.control.TableView; 
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode; 
import javafx.scene.layout.AnchorPane;

public class TestTable extends AnchorPane {

   @FXML private TableView myTableView; 

   public TestTable() { 
     FXMLLoader fxmlLoader = new FXMLLoader(
      getClass().getResource("/com/lynden/planning/ui/TestTable.fxml"));

      fxmlLoader.setRoot(this); fxmlLoader.setController(this);
       try { 
         fxmlLoader.load();
       } catch (IOException exception) { 
         throw new RuntimeException(exception); 
      } 
   } 
}

Finally, a new Scene can be created which includes both the TestTable and TestButton components that were constructed above.  Unfortunately, custom components can’t be added to the Scene Builder palette, so they must be inserted manually into the FXML file.  You just need to ensure that you have the proper import statements defined, and the TestTable and TestButton components can be inserted into the FXML code just as any native JavaFX component.

<?xml version="1.0" encoding="UTF-8"?>

<?import com.lynden.fx.*?>
<?import com.lynden.fx.table.*?>
<?import com.lynden.fx.test.*?>
<?import com.lynden.planning.ui.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?scenebuilder-classpath-element ../../../../../../../target/classes?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="766.0" xmlns:fx="http://javafx.com/fxml">
    <children>
        <TestTable layoutX="5.0" layoutY="4.0" />
        <TestButton layoutX="622.0" layoutY="157.0" />
    </children>
</AnchorPane>

When Scene Builder opens the FXML file you will see that both components are displayed on the new Scene

image

That’s it, hopefully this will help others who have been looking at adding custom components to their UIs that are designed with Scene Builder.

twitter: @RobTerp

Advertisements

23 thoughts on “Creating Custom JavaFX Components with Scene Builder and FXML.

  1. Pingback: Drag and Drop With Custom Components in JavaFX | Rob's Blog

  2. Pingback: JavaFX links of the week, September 23 // JavaFX News, Demos and Insight // FX Experience

  3. Pingback: Java desktop links of the week, September 23 « Jonathan Giles

  4. I have this all working, however, I really need to use property injection to get a reference to the custom controls into the controller that encapsulates them. I have been unable to do that. The “id” field seems to have no effect. Any suggestions?

    • I’m seeing the same behavior as well when attempting to access the custom components from the parent component’s controller class. I’ll have to take a look at this when I return to the office next week. If you find a solution in the mean time I would be interested to hear how it works.

      Thanks,
      -Rob

  5. Great tutorial, but informations about import path at the end of the article are not clear. Is it path to fxml file, or maybe Java (controller) class file, or maybe both?

  6. Hi Rob.
    Thanks for a great tutorial, i have tried following it a couple of times now, but whenever i reach the last step and try to view my FXML file with the custom components added i get the following error in SceneBuilder:
    Missing types are: [Table]

    However if i compile the project it shows up just perfectly fine, any suggestions?

    Best,
    Simon Kragh

    • Thanks for the feedback Simon. In your FXML file do you have the classpath of your custom component defined just below the import statements, such as:

      or

      • I just noticed it filtered out my XML snippets in my response. I’ll take the lt,gt tags off and see if it works.

        ?scenebuilder-classpath-element ../../../../../../../target/classes?

        or
        ?scenebuilder-classpath-element split-flip-1.0.0.jar?

  7. As of JavaFX Scene Builder 2.0 b7, you can permanently import custom controls into the library. Use the Library panel’s pull-down menu (you can access it by clicking small down-arrow at the top of the library panel), and select “Import JAR/FXML file”.

  8. Great post, thanks.
    But I am wondering how this will be performing when multiple instances of a custom component are loaded. Let’s you want this custom component next to each row in your example. This means N instances are created of this component. But will this result in the same fxml file being read N times? Or is this a non issue?

    • Yes, I believe the file will be read N times, as the read takes place in the constructor of the component, but what I am not sure, is what sort of performance penalty will be paid for this. I guess it would likely depend on how many custom components will be added to the Scene.

  9. Yep. This works so far. But: I do want to integrate a customized FXML-Widet into the main FXML (for example a customized text widget with restricted input), but need to access the values in customized widget from the main FXML too. For example to further process the value, or to clear the value. I did not find a method to achieve such a behaviour.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s