A JavaFX HelloWorld using Java 9’s Project Jigsaw in 60 seconds

By now you’ve probably have heard of Java 9’s new module system a.k.a. project Jigsaw. If you don’t know about Java 9’s new module system, you should visit Mark Reinhold’s paper on The State of the Module System. Also, you should check out @nipafx Nicolai Parlog’s excellent blog at http://blog.codefx.org There he goes into great detail about Java 9’s new module system and many scenarios.

In this article I will attempt to show you how to create a JavaFX Helloworld application using Java 9’s module system in 60 seconds.


As of this writing Java 9 is still in the early access phase which means you’ll need to grab the latest builds at https://jdk9.java.net/download/

  • JDK 9 EA build 114 or greater (JDK 9 EA)


Assuming you’ve installed your JDK and have the appropriate environment variables set. Also, you’ll want to get to the command prompt or terminal and type: java -version to verify the installed JDK. Eg.

Screen Shot 2016-04-25 at 12.09.37 AM

Step 1: Create a directory in your home directory for your project such as the following for Windows OS, Linux, and MacOS respectively. Also, create a src directory under your helloworld project directory.

  # Windows
  c:\Users\myusername>md helloworld
  c:\Users\myusername>md helloworld/src
  # Linux
  /user/home/myusername $ mkdir -p helloworld/src

  # Mac
  /Users/myusername$ mkdir -p helloworld/src

cd helloworld  

Step 2: Create a directory using a simple naming convention based on Java 9’s new way to organize source code and modules.

Create a directory named as your module eg: com.mycompany.helloworld. Assuming your current directory is <User’s Home dir>/helloworld/

   mkdir src/com.mycompany.helloworld

Step 3: Create directories based on your package namespace of the HelloWorld.java file. In this simple example the main Helloworld.java will be created using the following directory structure:

 mkdir -p src/com.mycompany.helloworld/com/mycompany/helloworld

The directories should look like the following:

        <User Home dir>/

Step 4:  Create a module-info.java file. This lets the compiler know which core module dependencies the application needs to compile and run such as javafx modules. Create a file named module-info.java under the directory helloworld/src/com.mycompany.helloworld. Copy and paste the code below into the module-info.java file. Use vi, nano or notepad.

module com.mycompany.helloworld {
   requires javafx.base;
   requires javafx.graphics;
   requires javafx.controls;
   exports com.mycompany.helloworld;

Step 5:  Create the HelloWorld.java application file. The file will be created in the directory helloworld/src/com.mycompany.helloworld/com/mycompany/helloworld/ . Copy and paste the code below into the HelloWorld.java application.

package com.mycompany.helloworld;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

 * A JavaFX Hello World
public class HelloWorld extends Application {

    * @param args the command line arguments
    public static void main(String[] args) {

    public void start(Stage stage) {
       stage.setTitle("Hello World");
       Group root = new Group();
       Scene scene = new Scene(root, 300, 250);
       Button btn = new Button();
       btn.setText("Hello World");
       btn.setOnAction( actionEvent -> 
                 System.out.println("Hello World"));

Step 5:  Compile the source code with the -d option with the location of compiled module. The directory for the new helloworld module is mods/com.mycompany.helloworld .

javac -d mods/com.mycompany.helloworld src/com.mycompany.helloworld/module-info.java src/com.mycompany.helloworld/com/mycompany/helloworld/HelloWorld.java

Step 6:  Execute the Hello World application as a module. After compiling the module into the mods directory you will now use Java 9’s new -modulepath option to specify the compiled module’s directory. Also, you will specify the -m option to execute the module and its main class HelloWorld. Use the following command:

java -modulepath mods -m com.mycompany.helloworld/com.mycompany.helloworld.HelloWorld

The output of the previous command:

Screen Shot 2016-04-26 at 1.42.13 AM



Not sure if you’ve taken more than 60 seconds, but assuming your environment is setup and the JDK 9 is installed you should be able to cut and paste the code in seconds. I find the new Java 9 module system pretty straight forward. Although there is a little extra typing in order to let the compiler know where modules are, it’s really not that different than the -classpath option.

I can see how large projects can break apart components as modules and benefit from it.  I believe these are truly exciting times in the Java world because tools will be able to build thin executables, thus faster load times. I feel it’s been a very long time coming, but a very needed feature that will encourage us to write, manage and deploy modular software.


Shadow Fields vs. Property Accessors Interface Round 3

This is round 3 of the Shadow Fields vs Property Accessors Interface. If you are new and not sure what the fuss is about please check out my previous post or my first post on the topic of saving memory when developing JavaFX applications. As a Java developer my main concern is having a good balance between performance, memory usage and lowering boilerplate code (ease of API use) when developing JavaFX domain models. Usually, application frameworks provide a model view controller(MVC) or presentation model pattern to separate UI code from domain objects. In fact what comes to mind is that domain model type objects should be easy to create or generated (IDEs). In this blog entry you will see results of Round 3 with two parts. Part 1 was implemented using an idea from Marcel Heckel and Part 2 is an implementation that I eventually settled with based on performance, memory usage and ease of use.

Disclaimer: Use any of the code at your own risk. This is purely experimental and should not be used in production. This is a work in progress.

The latest code is here —> [PropertyAccessors interface]

Recap of Round 2

Although, the last round (round 2) indicated that my Property Accessors strategy was slightly better in memory consumption than the standard (fat) property objects strategy, it was still disappointing in terms of performance when creating 2,000,000 objects of an Employee type class having native type objects. I still was not happy with the memory usage of my round 2 implementation compared to Dirk’s implementation. If you just care about my final results of Round 3 just skip to the Results section.

Because, there might be a new Round please check out the current code here  if you decide to use it or assuming Dirk decides to accept my pull request head over to his Github account here.😉

In round 2, I used a hash map lookup that can be quite slow as more and more fields are added with a O(1) time complexity (search). Interestingly, Marcel Heckel commented to suggest a simple approach of creating an indexed array of objects which will not not only save more memory but will be much faster. Compared to a key/value pair lookup a direct index access to a field is definitely the way to go. Although, Marcel’s code is faster, it still takes up more memory than Dirk’s Shadow Fields code. The extra memory is actually taken up by the preallocating of an array that will hold the values for the each field. Even if they are all nulls the array itself is created for each employee object. I implemented Marcel’s strategy here (line 23). Let’s look at the results of the array of indexed fields strategy.

Part 1: Using an Array of Indexed Fields

private final Object[] modelProperties =
                               new Object[FIELDS.values().length];
    public Object[] getModelProperties(){
        return modelProperties;

TEST: Objects Not Using Property Fields

Shown below is using a mix of Marcel’s indexed array idea and my way of specifying the property name using enum types to denote fields as property fields.

Screen Shot 2016-04-07 at 12.18.01 AM

Objects that aren’t using JavaFX properties compared to standard (fat) objects with all fields as JavaFX properties. This implementation uses an array index for each field and an array to hold each value.

Above you will notice the check box is unselected to indicate not to create JavaFX properties on the domain object (not using the xxxxProperty() methods). You’ll notice that the performance has dramatically increased compared to round 2’s code and memory usage also reduced. In the figure above the Property Accessor interface is at 16MB more than the Shadow Fields’ pattern implementation. In part 1 of thin objects performance and memory usage Shadow Fields is the clear winner. However, Shadow Fields is still not as clean to implement. Another thing to note is that Property Accessors interface is just shy of 14 milliseconds for 2 million objects! As we’ll see later in Part 2 Bringing back Private Instance Variables as Fields the Property Accessors interface will really shine with memory usage.

TEST: Objects Using of Property Fields

The following is the results when all fields of an object is using JavaFX properties.

Screen Shot 2016-04-07 at 12.24.22 AM

Objects that are using JavaFX properties compared to standard (fat) objects with all fields as Javafx properties. This implementation uses an array index for each field and an array to hold each value.

Here, you’ll notice the Accessor columns (Property Accessors interface) at 2 million objects performs at 916 milliseconds with a 576 MB use of memory. In this case the standard (fat) object is the winner as far as memory space at 544 MB. Shadow Fields wins on performance on every round so far.

One minor detail with Marcel’s code example (in the comments section) is it doesn’t take into account the string name of the property when creating a new property object instance. For example the following statement shows the variable totalProperty with the property named ‘total‘ which matches the totalProperty() method. Firing the name of a property during change is important for reading code, testing and tooling.

Property totalProperty = new SimpleIntegerProperty(this, “total”, new Integer(5));

To have both a named field and an index like Marcel’s idea, I simply created an enum declaring each field property. These enums are created on the Employee class.

// Part 1 implementation
public class EmployeePropertyAccessor implements PropertyAccessors{
    public enum FIELDS {
    private final Object[] modelProperties =
                               new Object[FIELDS.values().length];

    public Object[] getModelProperties(){
        return modelProperties;

    // The rest of the code...

Above you will notice how the model Properties array will be created based on the number of defined fields (enum FIELDS). I use the FIELDS.value().length to define the size of the array. Also, the PropertyAccessors interface (Part 1’s implementation) forces the developer to implement the getModelProperties() method. Here, I just returned the modelProperties‘ reference to an array of objects. It isn’t very pleasant to ‘have to‘ implement an array and a getModelProperties() method .

In part 2, of this article, I implemented things differently where the developer isn’t forced to implement a modelProperties array and a getModelProperties() method. I will solve this issue where the code will look much cleaner and performant (user of the API’s perspective).

Part 2: Reintroducing Instance Variables

Part 2, I will be adding private instance variables back into the Employee class (EmployeePropertyAccessor) to hold the field values instead of an array like in Part 1. My idea was to have a field variable be mutually exclusive to either point to a native object type or a JavaFX property, thus saving memory compared to the Shadow Field pattern code. Since, the Shadow Fields code uses two variables to represent a field value, it will have an extra reference which will inevitably increase its memory when the object uses properties. As you can see below the code will look similar to part 1, but also will have a static block to register the property fields in the class. This is important because some instance variable you may not want participate as JavaFX properties.

// Part 2 implementation
public class EmployeePropertyAccessor implements PropertyAccessors {

    private Object name;
    private Object powers;
    private Object supervisor;
    private Object minions;

    enum FIELDS {

    static {
        // register fields one time.
        // (Warning: enum's ordinal value is reassigned an index number)
        registerFields(EmployeePropertyAccessor.class, FIELDS.values());

    public EmployeePropertyAccessor(String name, String powers) {

    public final String getName() {
        return getValue(FIELDS.name, "");
    public final void setName(String name) {
        setValue(FIELDS.name, name);
    public final StringProperty nameProperty() {
        return refProperty(FIELDS.name,
SimpleStringProperty.class, String.class);

    // The rest of the code...

The code listing above does some interesting magic when calling the registerFields() method. The FIELDS enums’ ordinal values are reassigned using reflection giving each a new id as an index into an array. This provides immutable enums while also containing a unique identifier for each field to be accessed fast via an index. Since enum are used to represent fields to be used as properties, the ordinal values are meaningless in other contexts. This means: Who cares, if the ordinal value is reassigned on these declared enums? They are only used for this purpose only ‘to register fields‘.

TEST: Objects Not Using Property Fields [NEW]

Shown below is the test results using the new implementation of the Property Accessors interface API. The test below shows when not using property fields compared to the standard fat object.

Screen Shot 2016-04-09 at 12.29.32 PM

A test that compares standard objects (all fields using properties) vs objects using native objects. Property Accessors interface API now uses instance variables as fields instead of a reference to an array.

As you can see above the new implementation of the Property Accessors interface is the clear winner for memory usage and ease of use. The performance is slightly slower than part 1’s implementation but the savings in memory is worth it. You’ll notice that the Shadow Fields’ memory usage is 16 MB more than Property Accessors’ usage.

TEST: Objects Using of Property Fields [NEW]

Shown below is the test results using the new implementation of the Property Accessors interface API. The test below shows when using property fields compared to the standard fat object. (The check box is checked underneath the Start button)

Screen Shot 2016-04-09 at 12.36.02 PM

Results of Round 3

Below are bar charts I threw together based on the results in the tables. I felt people like to see charts instead of tables, cells and text.😉


Test results of performance when objects aren’t using JavaFX properties. Smaller number (in milliseconds) is better.


Test results of performance when objects are using JavaFX properties. Smaller number (in milliseconds) is better.



Test results of memory usage when objects are not using JavaFX properties. Smaller number (in megabytes) is better.



Test results of memory usage when objects are using JavaFX properties. Smaller number (in megabytes) is better.



Based on the results my goal was definitely achieved (IMHO) where I originally wanted code to be simple to read and easy to implement when objects may or may not use JavaFX properties (with the added benefit of saving memory when fields aren’t using JavaFX properties [native types]). Although, performance-wise Shadow Fields won on all of test runs, Property Accessors interface wasn’t far behind. When not using properties Property Accessors interface  beats the Standard object strategy by a mere 5 milliseconds when creating 2 million records.

When it comes to memory usage with creating 2 million objects and when the strategies were  not using properties as fields, the Property Accessors interface is clearly the winner with a savings of at least 16MB compared to the Shadow Fields pattern and a 240MB savings compared to the Standard Properties code. Last, but not least is the results when objects are using properties as fields, Property Accessors interface ties with the Standard objects strategy regarding memory consumption. The Shadow Fields strategy uses is at least 20MB more than the other strategies.

Even though Properties Accessors interface is slightly slower (by a small difference in milliseconds) when using or not using all fields as properties for 2 million objects, I am convinced the API can be used on any JavaFX application size for the ease of development of domain models and objects. I encourage others to test the code themselves before making the decision to use the API. Please be advised that the code isn’t considered production ready and is very experimental. This is a work in progress, so until I get to eat my own dog food (at work) I can’t really recommend that you use the Property Accessors API. I’ll restate the disclaimer below:

Disclaimer: Use any of the code at your own risk. This is purely experimental and should not be used in production. This is a work in progress.

Feel free to comment and subscribe. Enjoy and happy coding!





Shadow Fields vs. Property Accessor Interface Round 2

If you guys haven’t noticed a (light-hearted) showdown between Dirk Lemmerman and me, let me quickly mention how we got to this point. For starters, Dirk created a JavaFX tip 23: “Save Memory Shadow Fields for Properties” to help application developers save memory when using JavaFX Properties. Pretty impressive knowing that you can save memory when objects aren’t needing to use JavaFX Property objects.

While looking at the code I couldn’t help but notice boilerplate code that drove me bonkers, so I decided to make a simple API that also took into account the interesting Shadow Fields pattern used by Dirk’s example. The API I created aka Property Accessor Interface comprises of default methods that easily allows developers to implement the interface as opposed to extending an abstract class to avoid Java’s single inheritance rule. To see the Property Accessor interface code I blog about it here. To my surprise Dirk created yet another blog entry to benchmark all three approaches. Below is the chronological order of the blog posts thus far if you are keeping up with all the fun.

  1. Save Memory Shadow Fields for Properties by Dirk Lemmerman
    Introducing the concept of Shadow Fields
  2. JavaFX Tips to Save Memory! Shadow Fields for Properties and Observables by Carl Dea
    My attempt to save memory and reduce boilerplate code.
  3. Shadow Fields vs. Property Accessor Interface by Dirk Temmerman
    A benchmark application to test the three approaches of objects having properties and raw datatypes for fields.
  4. Shadow Fields vs. Property Accessor Interface Round 2 by Carl Dea
    A revisit of the Property Accessor Interface to reduce the memory usage by centralizing a map of values.

As it turns out my implementation was the worst of the three even with the bloated object with already instantiated property fields according to post #3 above.😦 Because I rushed into things and didn’t know the issue until Dirk’s post #3 above. Well, I’m not ready to wave the white flag and besides I still have a few tricks up my sleeve.

Next, you will get to see what I did to reduce the memory usage of the Property Accessor interface strategy. To see the code changes please see the code at the Github here. The only change I made was centralizing the Map containing the values. As you can see below the memory is much lower compared to Dirk’s post #3 above. However, event though I didn’t beat Dirk’s implementation using shadow fields I did slightly better than the standard object approach.

An updated Property Accessor Interface implementation using a centralized map.

An updated Property Accessor Interface implementation using a centralized map.


Although I’ve only made a simple change by removing the hash maps from every object and centralizing all values to a single map the Property Accessor interface still didn’t trim memory as low as the Shadow fields technique. I may explore other techniques such as weak references or take a look into memory mapped files. I doubt I can reduce things any further, but I believe a relatively small to medium application could use the Property Accessor interface to rapidly build apps. They (developers) could use proper pagination to avoid large lists. One last idea would be to create an annotation that could even reduce the boiler plate code.

Let me know ow what you think? Any suggestions?

JavaFX Tips to Save Memory! Shadow Fields for Properties and Observables

A TreeTable control holding employees.

A TreeTable control holding employees.

   In the world of JavaFX the Properties API allows UI developers to bind values to UI controls. This capability is surprisingly easy, however when object models use properties too often an application can quickly run out of memory. I usually will write two separate objects such as a pojo class and a presentation model object. This technique is often used in Swing based applications. From a  JavaFX perspective, you could just create one object with properties to allow observers (listeners) to update values. This sounds fine right? Not exactly because the main issue is when all of the object’s (pojo) attributes (fields) are properties which also wrap actual values the programmer (user of the api) may not want to bind or use properties at all, but only want to access the actual values. So, what is a JavaFX developer to do?

I often go to the blog Pixel Perfect by Dirk Lemmermann who will often post very useful JavaFX tips. Recently, Dirk blogged about how to save memory using an interesting pattern called Shadow Fields.  To see his post please visit his blog entry JavaFX Tip 23: Save Memory! Shadow Fields for Properties.. Dirk’s JavaFX tip does help solve the problem mentioned above (lessening the heap), however I noticed boilerplate code that has to exist to provide (a smart determination) to the caller of whether the return is the actual object or the property wrapper object. For example, instead of returning an IntegerProperty object when calling get or set methods, the code will return an int or Integer value, thus saving memory. Furthermore, the code declares two variable to hold one of the two value types. For example:

private String _title = "Untitled"; // shadow field
private StringProperty title;

I felt I could make things more concise and possibly saving more memory. And reducing the boilerplate code. I decided to create an interface with Java 8’s default methods that will handle managing actual values and properties. The user of the API will simply create a domain class that implements the following interface:

Interface PropertyAccessors

An interface providing accessor methods to provide smart determination of actual object value or the JavaFX property wrapper object. The user of the API must implement one method called getModelProperties() which returns a Map of property name (String) and value (Object). The value can be an actual object or a Property type object. The code below also will support Observable lists.

package com.jfxbe;

import javafx.beans.property.Property;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

 * Provide default methods to support the similar
 * capability of the shadow fields pattern.
 * To save memory object values don't have to be
 * wrapped into a Property object when using getters
 * and setters, however when calling property type methods
 * values will be wrapped into a property object.
 * Default methods for Observable lists are provided too.
 * Created by cpdea on 4/3/16.
public interface PropertyAccessors {

    Map<String, Object> getModelProperties();

    default <T> T getValue(String name, Object defaultVal) {
        Object p = getModelProperties().get(name);
        p = p==null ? defaultVal : p;
        return (T) ((p instanceof Property) ? ((Property) p).getValue(): p);

    default void setValue(String name, Object value) {
        Object p = getModelProperties().get(name);
        if (p instanceof Property) {
        } else {
            getModelProperties().put(name, value);

    default <T> T refProperty(String name, Class propClass, Class rawValType) {
        Object p = getModelProperties().get(name);
        Property prop = null;

        try {

            if (p == null) {
                Class[] constructorTypes =
                        new Class[]{Object.class, String.class};
                Constructor<Property> propConstr =
                prop = propConstr.newInstance(this, name);
            } else if (rawValType.isInstance(p)) {
                Class[] constructorTypes = new Class[]{Object.class,
                        String.class, rawValType};
                Constructor<Property> propConstr =
                prop = propConstr.newInstance(this, name, p);
            } else {
                prop = (Property) p;
            getModelProperties().put(name, prop);
        } catch (Exception e) {
        return (T) prop;

    default <T> List<T> getValues(String name, List<T> defaultValue) {
        Object p, o = getModelProperties().get(name);
        p = o;
        o = o==null ? defaultValue : o;
        if (!o.equals(p)) {
            getModelProperties().put(name, o);
        return  (List<T>) o;

    default <T> void setValues(String name, List<T> newList) {
        Object list = getModelProperties().get(name);
        if (list == null || !(list instanceof ObservableList)) {
            getModelProperties().put(name, newList);
        } else {
            // Should the list be totally replaced? below clears and adds all items
            ObservableList<T> observableList = (ObservableList<T>) list;

    default <T> ObservableList<T> refObservables(String name) {
        List list = (List) getModelProperties().get(name);

        if (list == null) {
            list = FXCollections.observableArrayList(getValues(name, new ArrayList<>()));
            getModelProperties().put(name, list);

        if (! (list instanceof ObservableList)) {
            list = FXCollections.observableArrayList(list);
            getModelProperties().put(name, list);

        return (ObservableList<T>) list;

Employee Class

A class named Employee which implements the PropertyAccessor interface. Below you will notice the property name of each field is declared using a public static final String. For example, the employee’s name is:

public static final String NAME_PROPERTY = “name”;

For the accessor methods such as getters, setters and xyzProperty() you will notice the calls to the default methods in the PropertyAccessor interface.

package com.jfxbe;

import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 * A hybrid domain and model object using the shadow field pattern to save memory.
 * Created by cpdea
public class Employee implements PropertyAccessors{

    /** This is a map to hold properties and observables */
    private Map<String, Object> modelProperties;

    public static final String NAME_PROPERTY = "name";
    public static final String POWERS_PROPERTY = "powers";
    public static final String SUPERVISOR_PROPERTY = "supervisor";
    public static final String MINIONS_PROPERTY = "minions";

    public Employee(String name, String powers) {

    public Map<String, Object> getModelProperties() {
        if (modelProperties == null) {
            modelProperties = new HashMap<>();
        return modelProperties;

    public final String getName() {
        return getValue(NAME_PROPERTY, "");
    public final void setName(String name) {
        setValue(NAME_PROPERTY, name);
    public final StringProperty nameProperty() {
        return refProperty(NAME_PROPERTY, SimpleStringProperty.class, String.class);

    public String getPowers() {
        return getValue(POWERS_PROPERTY, "");

    public final StringProperty powersProperty() {
        return refProperty(POWERS_PROPERTY, StringProperty.class, String.class);

    public final void setPowers(String powers) {
        setValue(POWERS_PROPERTY, powers);

    public final Employee getSupervisor() {
        return getValue(SUPERVISOR_PROPERTY, null);

    public final ObjectProperty<Employee> supervisorProperty() {
        return refProperty(SUPERVISOR_PROPERTY, ObjectProperty.class, Employee.class);

    public final void setSupervisor(Employee supervisor) {
        setValue(SUPERVISOR_PROPERTY, supervisor);

    public final List<Employee> getMinions() {
        return getValues(MINIONS_PROPERTY, new ArrayList<>());

    public final ObservableList<Employee> minionsObservables() {
        return refObservables(MINIONS_PROPERTY);

    public final void setMinions(List<Employee> minions) {
        setValues(MINIONS_PROPERTY, minions);



So, there you have it, a solution to in an attempt to eliminate two variables and other boilerplate code. I haven’t actually tested the code with a large amount of data, so maybe in another post or some lucky reader will create a test comparing all three (object with all properties, Dirk and mine) implementations.

The possible downside to this approach is probably serializing the object when used with RMI servers. I’m sure there are other possible downsides, but for now most use cases this might be easier and cleaner code to deal with.

Please feel free to comment. Subscribe if you like this article.🙂



Raspberry Pi with Java: Programming the IoT (Book Review)


Cover of the book Raspberry Pi with Java: Programming the Internet of Things (IoT)

Raspberry Pi with Java: Programming the Internet of Things (IoT) Embedded Application Development for Home and Industry

Greetings Java/JavaFX/Raspberry Pi fans!,

Before beginning this book review it was brought to my attention that I had to disclose lawyer speak in order to comply with FTC rules relating to bloggers.

Disclosure of Material Connection: I received this book free from Oracle Press / McGraw-Hill Education (Publisher) In exchange for a book review. I was not required to write a positive review. The opinions I have expressed are my own. I am disclosing this in accordance with the Federal Trade Commission’s 16 CFR, Part 255: “Guides Concerning the Use of Endorsements and Testimonials in Advertising.”


It is the year 2016, and by now we should be at more than a billion connected devices related to the Internet of Things (IoT) which numerous firms have predicted. If you’re like me a person who loves to tinker and discover things you have probably heard about the Raspberry Pi. On my journey to learn all things Pi I’ve come across many books related to the Raspberry Pi that utilized various programming languages, however when it came down to the Java language the books were pretty scarce.

Look no further, a new book has finally arrived that focuses on Java technologies to drive your Raspberry Pi projects. In this blog entry I will be reviewing the book Raspberry Pi with Java: Programming the Internet of Things (IoT) by Stephen Chin with James L. Weaver  (Oracle Press). Technical editor by Mark Heckler.

Book Review

The two book authors are some of the most respected in the IoT, Java and JavaFX communities. Both Stephen Chin (Oracle) and James Weaver (Pivotal) are Java champions who are renowned speakers at many major developer conferences worldwide. The technical editor Mark Heckler (Pivotal) is also a well known Java geek who also speaks at many prominate conferences around the world.

For starters the authors begin with a very good introductory and summary of the chapters. After the summary of the chapters the book points out two links to download the source code for the book. Other programming books with source code usually point to their publishing company’s website. Fortunately, this book provides two places to obtain the source code. One at the publishing company (www.mhprofessional.com) and the other is hosted at the Github (https://github.com/RaspberryPiWithJava).

Chapter 1: Baking Pie

The authors gets you started by listing all the component parts and software necessary to develop on the Raspberry Pi. The instructions on how to setup and configure the Raspbian OS are thoroughly explained. I like how the authors discuss how to connect all the different Raspberry Pi models to your network. Keep in mind that the book was written prior to the announcement of the Raspberry Pi Zero model, so the book has no mention of it.

In chapter 1 they show you how to connect your Raspberry Pi using Ethernet or Wireless connection. After, successfully connected, the authors show you how to ssh into your Raspberry Pi remotely from the three major OS platforms (MacOS, Linux and Windows) through your terminal (command-line console). Once able to ssh into your Raspberry Pi you will be able to code/compile and run a Hello World Java console application.

Chapter 2: Your First Java Project

In Chapter 2, the authors begin by walking you through setting up the NetBeans IDE to remotely debug live running code on a Raspberry Pi. Once you get comfortable with the developer workflow, the authors start out with a cool (hot) project on brewing the perfect cup of coffee! When beginning a project the authors always start off with a Bill of Materials detailing what and where to buy parts for a project.

In this chapter it delves into APIs (JSR 80) that allows your Java code to communicate with USB ports (usb4j). The authors show you how to read information from a USB port on an electronic scale device. The scale is used to measure the weight of things such as ground coffee beans. This chapter ends with the discussion of the topic of Commercial Licensing and FOSS. Learning about licensing options can help you navigate through legal matters if you decide to go commercial with your Java/Raspberry Pi product.

Chapter 3: Binary Timer

The authors goal in this chapter focuses on how to use GPIO (general purpose input output) pins. The GPIO pins are how the Raspberry Pi talks to analog and digital components such as LEDs, DC motors and light sensors. In this section you will learn the fundamentals of electronics such as power, Ohms law and what resistors you will need to purchase, etc. I love one of the tip blocks on “What is the Worst You Can Do to Your Raspberry Pi“. This tip allows you to not feel intimidated when approaching a Raspberry Pi by explaining how rugged the Raspberry Pi computer actually is, and how to prevent mishaps or damaging the Pi.

The authors mention two Java libraries commonly used for accessing GPIO pins on the Raspberry Pi. One being the Device I/O library and the other Pi4J. In this section the benefits of using each library are fully detailed. This chapter is very hands-on by creating a basic project using LEDs on a breadboard that can count down in binary. Many Fritzing diagrams are presented for step-by-step instruction on how to wire-up components properly. In this chapter the authors mention helpful troubleshooting tips such as Java code to solve the button debouncing issues when dealing with physical buttons or switches in your circuits. Lastly, this chapter provides bonus content that teaches you how to measure and compare performance metrics when using the two Java libraries Device I/O library and Pi4J by turning LEDs on and off very rapidly. Here, both memory-mapped access (Low-level) vs Sysfs access (Higher-level) were compared. This will help you decide which strategy is best depending on your use-case.

Chapter 4: IoT Hat

Now with the fundamentals of the Raspberry Pi, Java and basic electronics out of the way, you can now tackle a magical project that will astonish friends and family. This project involves creating a magicians top hat with the ability to know what playing card was chosen without seeing the face of the card. The authors teach you about how to configure your Raspberry Pi to enable I2C, SPI, and UART protocols. This chapter focuses on learning about NFC/RFID devices such as smart card readers. Beware: This section involves soldering so get your flux on. Here, you will learn how to communicate with an RFID reader’s breakout board.

This project also teaches you about compactness and portability (cordless) because you will be hiding stuff in a top hat. To make things portable the Pi will use a WiFi adapter and USB cell phone charging battery. The authors will also take you through native libraries required for Java to communicate with the NFC device so don’t be alarmed if you encounter Make files and permissions (typical in the Linux world).

Chapter 5: Line Runner

After learning skills for compactness and portability from chapter 4 the authors show you how to reuse your skills to build an autonomous robot! This should be the very reason to get this book. In the Bill of Materials all the parts (Makeblocks) you will need are detailed thoroughly. The robot will be able to anticipate obstacle while capable of following a lined path on a floor surface (Delivering mail comes to my mind). This chapter is focused on sensors, motors, and mechanical construction. With sensors the authors take you through how to use infrared and ultrasonic capabilities. When using motors this chapter explains pulse width modulation (PWM) to control the speed of the robot. The Java code examples are quite straight forward and concise.

Chapter 6: Tea Station

Not a coffee drinker? but a Java fanboy well, this project is for all the tea lovers (including you) out there! This project is building a tea station to steep the perfect cup of tea. In this chapter the author discusses electronic scales (again) except ones having better precision due to tea leaves being extremely light in weight. The author goes on to discuss about temperature sensors that can determine how hot the tea should be when below the temperature of boiling water with very good accuracy. The author delves into serial (RS232 to TTL) communications with various vendors selling electronic scales (In chapter 2, USB was used). Learning this skill is invaluable because many older devices still use serial communications, so you can adapt your ideas with just about anything.

In this chapter the author really takes things to the next level compared to chapter 2 (brewing coffee), because he teaches you how to implement a snazzy JavaFX UI on a touchscreen device! Just like the chapter on brewing coffee the authors have an incredible depth of knowledge on teas and types of teas.

Chapter 7: Autonomous Drone

I’m sure you’ve heard a lot about the drone craze well this chapter will knock your socks off! The authors will be employing a quadcopter and the Raspberry Pi capable of flying autonomously. Don’t be afraid the drone in this project it will not hurt you. Interestingly, enough this chapter will use two WiFi adapters to be attached to the Raspberry Pi (Model B). One adapter is to talk to the drone itself and the other is used as a wireless access point (WAP) to remotely talk to the Raspberry Pi. In this chapter the author highlights an API called Autonomous4j by Mark Heckler. Mr. Heckler is also the technical reviewer of this book. I’ve actually seen the drone in action at a JavaOne conference where Mr. Heckler and Mr. Weaver conducted a live demonstration. The APIs discussed in this chapter are very easy to use for example the following are some of the Java methods:

  • takeoff() – Causes drone to start and take off.
  • goLeft/goRight(int speed) – Given the percent of speed to fly left/right (its left or right)
  • forward/backward(int speed) – Cause drone to go forward/backward given a percent of speed
  • goHome() – Drone flies back to where it lifted off from
  • land() – Land and stop.

Chapter 8: Retro Video Game Emulator

Whoa!? If you are an 80s or 90s kid who enjoyed arcades and game consoles (I know I did) then this chapter is about creating an Nintendo Entertainment System (NES) game console! Most of the parts from the bill of materials can be obtained from the popular electronics company Adafruit. The author teaches you how to build a game controller, attach a speaker, and attach a LCD touch display. This project will involve learning how to connecting GPIO pins to the Kippah board to control a touchscreen display. The author walks you through using a NES emulation Java library halfNES by Andrew Hoffman. As most of you know when dealing with emulators it isn’t legal to play game ROMs of popular games back in the day, unless you actually own the old game cartridge, so the author suggest heading over to a site having free games you can play. I’m sure if you own Mario Brothers you can get the game ROM and try it out. The author ends the chapter with more hacking tips such as overclocking your chip to increase the performance of your Pi. It’s a game so you need it to run fast!

Chapter 9: NightHacking RetroPi

After you’ve learned from chapter 8 on how to build a game console, this chapter will show you how to make a portable hand-held game device just like a Nintendo Game boy!  The author is thoughtful in discussing about the pros and cons on various 3D printers and existing DIY communities at large. This chapter points out all the necessary software to print parts for your hand-held game device. The author provides great illustrations to step you through creating a polished product.


This book has opened my eyes to innovative ideas using Java with the Raspberry Pi. The content is well organized and easy to follow. Often other DIY books have difficulty explaining the integration between hardware and software, but this book blends the two together elegantly. This book is very definitive in terms of the numerous topics, vendors, components, comparisons and implementation strategies. The authors hit on practically every topic relating to how to command and control (many types of) devices.

A good number of projects are very hands-on with an emphasis on the engineering side of things as opposed to the software side (solely a software developer). If you like to build cool gadgets and comfortable with the Java programming language I urge you to get this book.

My only issue (tiny) is the paperback book’s illustrations are in black and white (gray-scale) which can make it difficult to see things such as colored resistors in the Fritzing diagrams or JavaFX UIs (User Interfaces). I believe the PDF version might be in color, but I’ve not seen it yet (just a hunch). But, overall I give this book a two thumbs up. By far, this book is the most comprehensive book combining two great technologies with a plethora of amazing DIY projects to date.

FX Playground




Update: The FX Playground project can be found at: https://bitbucket.org/cdea/fxplayground



FX Playground is a JavaFX-based prototyping tool or live editor that eliminates the step of compiling Java code. This concept isn’t new, for instance the Web world there are many HTML5 playgrounds that offer online editors that enable developers to quickly prototype or experiment with various JavaScript libraries. This allows the developer to focus on visualizations or UI details without needing to set-up an IDE project or mess with files. Even older (pre-dating) than playgrounds are REPLs (Read Eval Print Loop) where dynamic languages such as Groovy, Python, Ruby, etc. provide an interactive interpreter command line tool to allow developers to quickly script code to be executed. Scala is a compiled language, but also provides a REPL tool.

After finishing the book JavaFX 8 Introduction by Example I noticed each example was created as separate NetBeans projects which seemed a little overkill for small examples. Because the book is based on Java the language each program needed to be compiled (via javac) prior to execution. Larger projects will typically need to be set-up with a proper classpath and resources in the appropriate directory locations. Even larger projects will also need dependencies which typically reside on Maven repositories.

JavaOne 2014

Based on timing I was able to submit a talk regarding JavaFX based playgrounds just in time. After awhile I was pleasantly surprised that my proposal (talk) was accepted. You can check out the session here. Also, I will be presenting with my good friend Gerrit Grunwald (@hansolo_). So, be prepared to see awe-inspiring demos. Since the talk is a BoF (birds of a feather) the atmosphere will be low-key and very casual. I hope to see you there!

The JavaOne talk is titled “JavaFX Coding Playground (JavaFX-Based Live Editor Tool) [BOF2730]”.  Based on the description you’ll find that the tool will be using the NEW! Nashorn (JavaScript) engine to interact with JavaFX primitives. The figure below depicts the FX Playground tool’s editor windows and a JavaFX Display area. Starting clockwise at the lower left is the code editor window allowing the user to use JavaScript (Nashorn) to interact with nodes. Next, is the JavaFX FXML editor window allowing the user to use FXML (upper left). The FXML window is an optional.  In the upper right, you will notice the JavaFX CSS editor window allowing you to style nodes on the display surface. Lastly, to the bottom right is the output area or better known as the DISPLAY_SURFACE.

FXPlayground's editor windows

FXPlayground’s editor windows

FX Playground in Action

Because FX Playground is still in development I will give you a glimpse of some demos that I’ve created on Youtube. The following are examples with links to videos.



There are plans to opensource the code, but for now there is much needed functionality before public consumption.

The following features are a work in progress:

  • Make use of FXML editor window.
  • Pop out the display panel into its own window
  • Save, SaveAs, and Load Playgrounds
  • Build software to be an executable for tool users. (90% done)
  • Make the tool capable of using other languages (JSR 223)

I want to thank Oracle corp. especially the following engineers who helped me (some of the engineers below are not Oracle employees):


The FX Playground project can be found at: https://bitbucket.org/cdea/fxplayground

CarlFX’s Channel – https://www.youtube.com/channel/UCNBYRHaYk9mlTmn9oAPp1VA

7 of the Best Code Playgrounds – http://www.sitepoint.com/7-code-playgrounds

NetBeans – https://www.netbeans.org

JavaFX 8 Introduction by Example – http://www.apress.com/9781430264606

Nashorn – https://wiki.openjdk.java.net/display/Nashorn/Main

Enzo – https://bitbucket.org/hansolo/enzo/wiki/Home

Harmonic Code – http://harmoniccode.blogspot.com/

JavaFX 8u20 Days of Future Past (Always On Top)

It’s been a long time since I’ve posted topics relating to JavaFX. So, if you are still following along, awesome!


In this blog post I want to blog about a very cool feature starting with JavaFX 8 update 20 that allows your application to always be on top of other applications. What this means is that on your desktop your JavaFX based application can be a floating widget that will remain above all other applications (z-order). An example would be a weather widget in the upper right corner never to be obscured by other applications. So, I’m very excited to share with you this amazing feature ‘Always On Top’.


In the past Java Swing developers would rely on the method Window.setAlwaysOnTop(boolean).  This feature allowed Swing developers to build native looking and native behaving desktop applications. Ever since JavaFX 1.x this very feature was highly requested (originally requested by Stephen Chin @steveonjava for the WidgetFX framework). This feature request is JIRA ticket RT-153. Figure 1 is the feature request shown with a status of ‘Resolved’.

Jira ticket RT-153

figure 1: Jira ticket RT-153


Although this feature didn’t get into JavaFX versions 1.x, 2.x and the version prior to Java 8u20, it is finally here now. For those who don’t know how to report bugs or file new features requests I encourage you to head over to the JavaFX JIRA system.

Example: Weather Widget

Assuming you know the basics of JavaFX since version 2.0 a typical application would consist of extending from the javafx.application.Application class. When developing JavaFX desktop applications the platform API would provide you with a (javafx.stage.Stage) window. The Stage object will have the following methods to access the always on top property.

  • alwaysOnTopProperty()
  • setAlwaysOnTop(boolean)
  • isAlwaysOnTop()

The following code snippet sets the Stage to be always on top using the method setAlwaysOnTop(boolean).

public class KeyholeDemo extends Application {

   @Override public void start(Stage primaryStage) {
      // code omitted...

   public static void main(String[] args) {

How it works

Shown in the listing above the start() method sets the stage to be transparent to be a JavaFX window without a title bar. This allows applications to have irregular shaped windows on the desktop. If a web person trolls you again about JavaFX ask them the following question: “Can  HTML5 create irregular shaped windows on the desktop? (always on top)”. Next, the stage is setup to be always on top via the setAlwaysOnTop() method.


After realizing that this highly requested feature was available I basically updated my old ‘KeyholeWidget‘ project at the Github and created a video demonstrating the widget on my desktop. Here is the video:

To see the full code listing visit the Github project ‘KeyholeWidget‘.


I hope you’ve enjoyed this cool feature (I know I did). As usual please leave comments below.

Happy coding,