Build a JavaFX + LeapMotion application with gradle

For SlideshowFX (which is an app I’m developing in JavaFX and using the LeapMotion controller) I am trying to use gradle as build and dependencies management system instead of the very well-known  maven. There are few steps I had to fight with to successfully build a self-contained application (aka native bundle). For those don’t knowing what that means take a look at the Oracle Documentation.

Disclaimer : I’m new in the gradle’s world so maybe a lot of things could be improved.


  • Having a JDK 8 up and running
  • Having the JAVA_HOME environment variable defined to point the the JDK 8 installation
  • Having gradle installed properly (version 1.11 used at the time this article was written)
  • Knowing gradle a little bit


The javafxpackager

In order to package a JavaFX application you can use the javafxpackager tool provided with the JDK. It allows you to create the application JAR and then the native bundle for your application.

To create the jar you will use the following command:

javafxpackager -createjar ...

You will also need to define some attributes according your application, like -classpath for the list of JARs and libraries your application is using, -appclass for indicating what is the Application class of your application, -srcdir and -srcfiles for indicating which files should be included in your JAR, -outdir for indicating where the JAR file will be created and -outfile for the name of the JAR file.

To create the native bundle you will use the following command:

javafxpackager -deploy -native ...

Building with gradle

In order to build your application with gradle, we will invoke the javafxpackager tool from gradle itself. A JavaFX plugin for gradle exists but I didn’t succeed in using it for my purpose. Indeed for LeapMotion you need some DLL and dylib files that weren’t included in the final JavaFX bundle so I decided to do it myself using gradle tasks. And this also allowed to have a better understanding of the javafxpackager tool instead of just using an IDE to generate my bundle.


In the build.gradle file, I configured all projects with the Java plugin and the source and target compatibility:

subprojects {
  apply plugin: 'java'
  sourceCompatibility = 1.8
  targetCompatibility= 1.8

Dependencies and libraries

For SlideshowFX I decided to use file dependencies. So first of all I declared the dependencies at the beginning of the build.gradle file:

ext {
  allLibs = new File(rootDir, '/lib')
  felix = fileTree(dir: allLibs, include: 'Felix/*.jar')
  json = fileTree(dir: allLibs, include: 'json/*.jar')
  jsoup = fileTree(dir: allLibs, include: 'jsoup-1.7.3.jar')
  junit = fileTree(dir: allLibs, include: 'junit-4.11.jar')
  leapmotion = fileTree(dir: allLibs, include: 'Leap/*')
  markdown = fileTree(dir: allLibs, include: 'markdown/*.jar')
  scribe = fileTree(dir: allLibs, include: 'Scribe/*.jar')
  textile = fileTree(dir: allLibs, include: 'WikiText/*.jar')
  velocity = fileTree(dir: allLibs, include: 'Velocity/*.jar')
  vertx = fileTree(dir: allLibs, include: 'Vert.x/*.jar')
  zxing = fileTree(dir: allLibs, include: 'ZXing/*.jar')

  jdk = System.env.'JAVA_HOME'

Those files collections will be used further for declaring dependencies for each project. For LeapMotion, all files are included: JARs, DLL, and dylib.

Build the jar

To build the JAR I decided to overwrite the default JAR task present in the Java plugin of gradle. We are going to follow these steps:

  • Copy all dependencies of the project to the libsDir folder
  • Build the -classpath attribute for the javafxpackager tool. Each JAR used by the application is adde to the classpath
  • Build the -srcdir/-srcfiles attributes for the javafxpackager tool. There will be many of these attributes because there are classes and resources
  • Build the javafxpackager command to execute
  • Execute the command

Knowing that here is the task definition:

task jar(overwrite: true) << {

  if (jdk != null && !jdk.isEmpty()) {

    if(!libsDir.exists()) libsDir.mkdirs()

    // Copying libs
    copy {
      from(new File(project(':SlideshowFX-markup').libsDir, project(':SlideshowFX-markup').archivesBaseName + ".jar"))


    def classpath = ""

    fileTree(dir: libsDir, include: '*.jar', exclude: archivesBaseName + ".jar").each {
      f ->
      classpath += + ","

    classpath += "."

    def javafxpackager = exec {
      workingDir "${project.projectDir.absolutePath}"

      commandLine "${jdk}/bin/javafxpackager",
                  "-createjar", "-v",
                  "-appclass", "",
                  "-classpath", "${classpath}",
                  "-outdir", "${buildDir}${File.separator}${}",
                  "-outfile", "${project.archivesBaseName}",
                  "-srcdir", "${}/classes/main", "-srcfiles", "com",
                  "-srcdir", "${}/resources/main", "-srcfiles", "com"

Build the native bundle

Now that we have the JAR, let’s make the native bundle. For this we will also create a task for achieving this.

task buildJavaFXBundle << {

  if (jdk != null && !jdk.isEmpty()) {

    def javafxpackager = exec {
      workingDir "${project.projectDir.absolutePath}"

      commandLine "${jdk}/bin/javafxpackager",
                  "-name", "SlideshowFX",
                  "-outdir", "${}${File.separator}dist",
                  "-outfile", "SlideshowFX",
                  "-srcdir", "${}${File.separator}${}",
                  "-appclass", ""

Tasks’ dependencies

Now that we have the needed tasks, let’s add some dependencies between them in order to include everything in the gradle lifecycle:

tasks['jar'].dependsOn 'classes'
tasks['jar'].dependsOn ':SlideshowFX-markup:jar'
tasks['buildJavaFXBundle'].dependsOn 'jar'
tasks['assemble'].dependsOn 'buildJavaFXBundle'

Now calling the assemble task makes it.

Why being a Rebel is hot and spicy?

I usually write technical articles about what is hot and spicy in software development, or at least what I think is hot and spicy. Well, I will make a little exception this time and write about why it is also hot and spicy being a RebelLabs author. If you’re reading this, you probably know what RebelLabs is: a house of geeky ninjas that like to write technical content about hot topics in our geeky development world. According Oliver White, head of RebelLabs:

Developers enjoy the additional “spice” of RebelLabs–we’ve managed to create a reliable content machine producing challenging, opinionated and humorous technical content for all software engineers to enjoy. Recently I saw this quote about RebelLabs by Rafael Winterhalter, in a recent Developer of the Week interview by DZone, and I think it sums things up very nicely: “I like RebelLabs a lot, especially since they manage to be both competent and humorous which is a rather rare combination.” —

Finding passion in the geeky world of development

As a geek, I’m passionate about software development, especially about Java and more recently, JavaFX. This passion leads me to go to people and say “Hey look, I discovered some pretty awesome new stuff”. But you can’t do this with your wife or your grandma, right? You won’t be understood … So frustrating …

But as passionate geek, I still need to tell somebody what I have discovered, tested and developed because I’m proud of it. Yeah you read right, proud of it. It is like being a kid having the latest trendy toy who shows everybody he has it. It is the same for me with software development. RebelLabs brings me the possibility of doing it, with a lot of fun.

I don’t need to write about old tools, APIs, languages and so on. I need to find a subject, find a way of making it attractive and interesting, and write. And when it’s published it’s like telling the world how proud you are. It is like your work being concrete and not only stored on your computer, right? Haven’t you ever felt that feeling of pride when you’ve developed the next most awesome API and nobody is using it?

The open source writer

We all know open source projects, developed by passionate ninjas to help other ninjas (or not) do their jobs better and make them easier by bringing them tools, APIs and other shiny stuff. I know a couple of those. One of them, Guillaume Scheibel (@g_scheibel and Hibernate OGM contributor) told me some time ago, that in the beginning it was not that easy to code in open source projects because you show the way you code to everyone and you have to accept remarks from others giving you advices of how doing things better. You have to accept remarks and sometimes it is not that easy. Writing is almost the same because you show the world what you’ve done and how you write. Double pressure.

I accept both because what you learn is much greater than this. Why is it? Because I work with guys that are as passionate as me and who like to teach you things about writing, tools and more. They don’t want to take you down in what you’re writing, but raising you up. And remarks are always constructive. It helps you do things better.

I also think this needs a little bit of courage. You, and I, have to be brave before publishing your first article. I needed some to accept the opinions of others, I needed some to accept the remarks and comments about my opinion, way of writing and way of thinking. I needed some to accept that other ninjas will take a look and possibly prove me wrong. But at the end the discussion will bring you a lot of point of view, a lot of ideas and you will always have the chance to be better next time.

Being visible

There is a really nice side effect of writing for RebelLabs: you are visible and you’re getting more and more known. People are reading your articles, looking at your Twitter profile, reading your blog and so on. It is a nice recognition to have people with more experience than you reading your articles, commenting on them and sometimes offering you their point of view.

You start to grow much more, and very quickly. And people can see that you are passionate, up to date, open minded and full of resources. It is a very positive image you’re giving of yourself.

You also benefit of the RebelLabs’ image, so you are more considered as experimented because if you’re not, you’re going to know it very quickly. So it is good for RebelLabs and it is good for you as well.

Hot and spicy instead of glory

To conclude, I write for fun. I write because I like to share my knowledge. I write because I’m passionate. I write because I like to write. I don’t write for any glory. I’m humble enough to admit there are plenty of ninjas out there that are thousands times better than me. But I am always looking for new challenges and I like to share them because maybe it could help other ninjas like you.

It’s a great opportunity to write for RebelLabs, and I like it very much. I can only encourage you to think about it, because being a Rebel is freakin’ awesome, and it’s hot and spicy!

Partial HTML generation from textile using eclipse Mylyn standalone

The title is pretty much explicit. For SlideshowFX, I needed to generate HTML content from textile, in order to define slide’s content. Looking for a lib, I found eclipse Mylyn that can be used in a standalone way. The library is pretty powerful but I have to look a lot at the sources in order to get the things done how I wanted to (#LukeAtTheSource power). Generally to convert a markup string into a HTML one, you create a MarkupLanguage as well as a MarkupParser and do the following:

final MarkupLanguage language = new TextileLanguage();
final MarkupParser parser = new MarkupParser(language);
parser.parseToHTML("h1. My little String");

The thing is that this code will create a whole HTML document (with html, head, body and so on tags). Me needs were to just get the HTML code corresponding to my string, e.g.

<h1>My little String</h1>

So the code should be changed to use a DocumentBuilder, like the following one:

final StringWriter writer = new StringWriter();
final DocumentBuilder builder = new HtmlDocumentBuilder(writer);
final MarkupLanguage language = new TextileLanguage();
final MarkupParser parser = new MarkupParser(language, builder);

// false indicates to not produce a whole HTML document
parser.parse("h1. My little String", false);


String htmlContent = writer.toString();

This is almost done except that Mylyn generates IDs (which is kind of normal right?) by using the content of the markup. In short, I wanted to avoid IDs’ generation but I could’t find a right and efficient way to do it. So I decided to ensure uniqueness of IDs by always getting the current timestamp. Maybe it’s not a wonderful solution, but for the purpose of this little tutorial it will be perfect. The main idea is to change the ID generation and for doing this, you have to override some classes, because the default ID generation strategy is stored as a static and final variable, and no setters are available. The following example demonstrates how to do it:

final StringWriter writer = new StringWriter();

// The generation strategy generates IDs using the current timestamp
final IdGenerationStrategy idGenerationStrategy = new IdGenerationStrategy() {
  public String generateId(String s) {
    return System.currentTimeMillis() + "";

final IdGenerator idGenerator = new IdGenerator();

final TextileContentState contentState = new TextileContentState() {
  public IdGenerator getIdGenerator() {
    return idGenerator;

// Override the language to return the created contentState used for the ID generation
final MarkupLanguage language = new TextileLanguage() {
  protected ContentState createState() {
    return contentState;

final DocumentBuilder builder = new HtmlDocumentBuilder(writer);

final MarkupParser parser = new MarkupParser(language, builder);

parser.parse(markupString, false);


final String htmlContent = writer.toString();

This is it. Enjoy.

Update your Scene in JavaFX

Usually it is very simple to update your scene in JavaFX. For example if you want to update the X and Y position of your nodes, you can often simply do some stuff like:


But this isn’t a good way of doing it. In JavaFX you have to be sure you are in the JavaFX application thread. But how can you know this?


But what if you’re not in that thread?

Platform.runLater(Runnable r);

So each time you would like to update your scene manually, you should check if you’re or not in the FX application thread. So let’s make a really simple helper class:

 * @author Thierry Wasylczenko
public class PlatformHelper {

    public static void run(Runnable treatment) {
        if(treatment == null) throw new IllegalArgumentException("The treatment to perform can not be null");

        else Platform.runLater(treatment);

The method run does the check for you. Finally you can use a lambda expression to execute that code:

final Node node = ... ; -> {

That’s it.

PathTextField: quick example of property usage in JavaFX


Properties and binding in JavaFX is a really interesting feature that sometimes is hard to illustrate. Recently I just faced a problem in CompilerFX: file paths entered by the user could be problematic. Indeed on some platforms path separator is \ and on others it is /. In Java you can often use / as path separator.


So in our example, you can choose many solutions like for example:

  • When the user submit the path in a text field, replace all \ by /;
  • When the user enter a \, use a key event to replace it;
  • Choose a more JavaFX way.

Let’s deal with the third solution. Have this ones in mind:

  • In JavaFX you have the properties, allowing you to listen for a change using a ChangeListener;
  • The text of a TextField is store in the text property.

You could implement the second solution listen previously but let’s work with a custom text field that will replace replace all \ by /.

public class PathTextField extends TextField {

    textProperty().addListener(new ChangeListener<String>() {
      public void changed(ObservableValue<? extends String> observableValue, String s, String s2) {
        if(!textProperty().isBound() && s2 != null) {
          textProperty().set(s2.replaceAll("\\\\", "/"));

In this component, we place a ChangeListener on the text property in order to replace all \ by /. Then you can use it in your FXML files for example.

TableView and ListValueFactory in JavaFX

The TableView control is pretty complete to use and very convenient. But the classical use of it specify that a line is represented by an instance of an Object, usually a property bean. But in some cases it would be very useful to have a line composed by multiple instances of a specific class, i.e. having an instance per column, and each column should display a particular property of your instance. A concrete example would be the management interface of translations in NetBeans. Indeed, this screen display all properties files of a particular resource bundle, having a column for the translations keys and as many columns as needed to display the translations for each keys.


As said above, we could need an instance of object per column, meaning multiple instances per line. So a line of the TableView should be a List<? extends Object>. The problem is to know which data to display in a particular column.


As you may know, you can set CellValueFactory on a TableColumn, which will display the value in the cell. For example, you can set a PropertyValueFactory that will look for a property of a bean, and will display it. But that works if you have a single Object per line, not a collection. So we will create our own implementation that will check a property of a bean inside a list.

public class ListValueFactory<T, V> implements Callback<TableColumn.CellDataFeatures<List<T>, V>, ObservableValue<V>> {
  private String propertyName;

  public ListValueFactory(String propertyName) {
    this.propertyName = propertyName;
  public ObservableValue<V> call(TableColumn.CellDataFeatures<List<T> , V> p) {
    int index = 0;
    ListIterator<TableColumn<List<T>, ?>> iterator = 
    TableColumn tmpColumn;
    while(iterator.hasNext()) {
      tmpColumn =;

      if(tmpColumn == p.getTableColumn())

    T object = p.getValue().get(index);

    try {
      Method method = object.getClass().getMethod(propertyName.concat("Property"));
      return (Property<V>) method.invoke(object);
    } catch (Exception ex) {
      Logger.getLogger(ListValueFactory.class.getName()).log(Level.SEVERE, null, ex);
      return null;

As you can see, the implementation is totally generic. First, we try to know the index of the column and we suppose that this index is the same index of the data in the list of data. WARNING: this is totally wrong if, in your UI, you move columns ; so take this into consideration because the implementation is not shown here. Once we have the index, we look for the data in the list, and finally, using so introspection, we look for the getter of the property in order to get the value. And that’s it.


To use this implementation in your code, you juste have to do the following:

TableView<List<Person>> tableView = new TableView<>();
TableColumn<String> columnOne = new TableColumn<>("First name one");
columnOne.setCellValueFactory(new ListValueFactory<List<Person>, String>("firstName"));
TableColumn<String> columnTwo = new TableColumn<>("First name two");
columnTwo.setCellValueFactory(new ListValueFactory<List<Person>, String>("firstName"));
tableView.getColumns().addAll(columnOne, columnTwo);

“Bind” components’ size to a MediaView’s size in JavaFX

The MediaView is a control allowing you to add videos and sounds to your JavaFX application. If you are playing a video, maybe you would like another control to have the same size. For example, you can have a video played next to an image that you would like to have the same height. The easy thing would like to do some property binding like this:

final MediaView mediaView = new MediaView(aPlayerInstance);

final ImageView imageView = new ImageView(anImageInstance);

But this code is wrong because the MediaView doesn’t have a height property. So in order to succeed in our goal, the MediaView has a boundsInLocalProperty which can be used to change the size of the ImageView in our case. Look at this code example:

final MediaView mediaView = new MediaView(aPlayerInstance);

final ImageView imageView = new ImageView(anImageInstance);

mediaView.boundsInLocalProperty().addListener(new ChangeListener<Bounds>() {
  public void changed(ObservableValue<? extends Bounds> observableValue, Bounds bounds, Bounds bounds2) {

Of course you have to do some nullity checks to make your code more robust.