Material Design in JavaFX

The last weeks I worked on a prototype to create a Material Design like UI with JavaFX. Google provides an awesome documentation about the Material Design and its guidelines. You can find an example here.

I tried to recreate some of the Material Design layouts and components in JavaFX. Here I don’t won’t to recreate everything but create a theme that is inspired by material design. By doing so I can feel free to change any point of the Material Design definition. I think the project is at a point were I can show it to you to receive some feedback and maybe contribution. Here are some pictures of a demo application that is based on the theme:
mat2

mat1

The source of the project can be found at GitHub. Currently this project provides more than the theme (and the name will change in future). The complete demo application is build without using any specific or complex layouts. By doing so it’s very easy for a developer that isn’t that good in layout and UI related stuff to create a cool looking application. How this can be done will be discussed in a future post.

The entry point of the demo application can be found at com.guigarage.sdk.demos.SimpleViewAppDemo1 and by starting this application you can play with the first demo. An overview of this application can be found in this video:

An overview of the Web Component specifications

WebComponents are a new W3C standard that is defined by some new specification:

  • Element Template
  • Shadow DOM
  • Custom Elements
  • HTML Imports

An overview about this specs and how they can be used in HTML can be found in the presentation that I did with Michael Heinrichs at JFokus in detail. Therefore I only want a short overview here.

Element Template

By using the template tag you can define a reusable template of a HTML hierarchy that can be reused and added to your DOM. Let’s say you define the following template:
template
Once you have defined this template you can create a instance in JavaScript and add it to the DOM of the page:
template_to_dom
By doing so you can reuse the defined template several times in your page.

Shadow DOM

Let’s say you have defined a template (or a web component as we will see later) and use it in your application. By doing so the DOM of your component will be added to the page DOM. If you than want to style your page by using CSS or access the page by JavaScript there are some pitfalls. As an example the following DOM is created and a component (green) is added to the regular DOM (blue). A node in the page and in the component uses the same ID or style class:
shadow-1
Maybe the component was created by a different developer or it is part of a 3rd party module. In this case you maybe don’t know about the internal IDs or style classes. When styling or modifying your application you would use the following code:

In both cases your code will affect the node in the regular DOM and in the component. But normally you don’t want to change the component. Therefore the Shadow DOM was introduced. By using the shadow DOM the nodes of the component are separated from the regular DOM:
shadow-3
Once this is done CSS or JavaScript changes won’t affect the component that is capsulated by the Shadow DOM. A component in a Shadow DOM can be created by using JavaScript:

Custom Elements

The Custom Elements spec makes use of templates and the shadow DOM. By doing so you can specify a component and add it to a page in a Shadow DOM. In addition the spec defines a lifecylce for components.
By using the Custom Elements spec you can define reusable tags for your components. Let’s say you want to define a activity stream like in Facebook or Twitter. To do so we want to create a custom element for the entries in this stream.
elements-1
Normally you need to define a div hierarchy for any entry in the stream. This ends in a lot of boilerplate code like shown in the following snippet:

This don’t look readable and what we really want to do is something like this:

This can be done by using Custom Elements. To do so we first create a template:

Once this is done we need to write some JavaScript code to create a custom element that is based on this template:

Once this is done the activity-card tag can be used in our application. In the JavaScript code a method called createdCallback is defined. This method is part of the Custom Elements lifecycle and will be called once the component is created. Next to this method the following methods are defined in the lifecycle:

  • createdCallback
  • attachedCallback
  • detachedCallback
  • attributeChangedCallback(attrName, oldVal, newVal)

HTML Imports

When using the first 3 specs we can define reusable components in our HTML page. But all the code is still part of our HTML (or JavaScript) file. This is ok if we only want to create a single HTML page. But when creating a big application you will have several HTML files and you don’t want to define the reusable components on any page. Therefore the import can be used. By doing so you can specify a reusable component in a extracted HTML file that can be reused on any page. By doing so it’s even easy to create components that can be shared between several projects.
Using the import is easy. You only need to specify an import link that points to the file that contains the component specification:

Once this is done you can simply use the custom component in the page.

Concusion

This is only a quick overview to the new specifications without going to much into details. If you want to learn more you should have a look at our slides or additional documentation on the web.

A god starting point is the webcomponents.org page that contains a lot of documentation.

When trying to create your first own web component you will maybe see a big problem: Today most of the modern browsers don’t support this new specs.
wc-browser-support
As a workaround you can use the webcomponents.js polypill that will add the support of the shown specs to mostly all evergreen browsers. I plan to give an introduction to this polypill in a separate post.

A quick overview to the DataFX MVC and Flow API

This is a short overview of the controller and flow API of DataFX that I have written for the JSR377 mailing list. If you want to discuss the architecture in general please add a reply to the mailing list.

DataFX provides a MVC approach that adds a lot of API sugar to the FXML API of JavaFX. As a first example you can find a simple controller here:

DataFX Controllers supports a lot of standard annotations like @PostConstruct. In addition the @ViewNode and @ViewController Annotation can be used to provide a link to the view. @ViewNode does mainly the same as @FXML but provides additional functionalities. Actions can be defined by an unique id. Therefore you can use Annotations to bind controls to actions. If you want a action to be called in a background thread you only need to add the @Async Annotation to the method.

Next to this there are some special annotations to inject DataFX related Objects like an exception handler or the DataFX concurrency toolkit. Here is an example:

On top of the MVC API is the Flow API. By using this API you can define flows in your application. By doing so you can define links between views or actions that will open a specific view. A Flow can easily defined by using the controller classes:

When using a flow you can define actions as global actions for the flow or actions that are view specific.

Next to this the Flow API adds a lot of new annotations. By adding the @BackAction annotation to a node like a button the flow will navigate back to the last view once the button is clicked. Instead of defining the links in the flow definition you can use the @LinkAction(NextViewController.class) annotation.

In addition the Flow API provides CDI by using @Inject. To do so 4 different scopes are defined:

  • application scope (singleton)
  • flow scope (same instance will be injected in every controller / view / model of the flow)
  • view scope (same instance will be injected in the controller / model of the view)
  • dependend (always inject a new instance)

In addition DataFX provides a event system. This can be used to handle events between 2 separated flows, for example. Each event type is defined by a unique id. The following code snippet defines two controllers that can be used in complete different parts of the application and don’t know each other. By using the event system the first controller can send events to the second one by clicking the button:

If you want the async events you only need to add the @Async annotation to the producer or / and receiver. By doing so you can create events on a background thread that will be received on the platform thread.

DataFX provides a PlugIn API that can be used to define additional components / plugins that will be managed by DataFX. Therefore you can define two types of Annotations: A injection annotation that can be used to inject specific objects or a handler annotation that can be use to do some stuff with objects. Here are two examples:

Example A
DataFX provides a plugin for feature driven development. By doing so you can define nodes in your controller like this:

Now you can use the togglz API to define feature toggles and change them at runtime. If you for example disable the PLAY_FEATURE the playButton will become hidden. This is en example for a plugin that provides handler annotations.

Example B
DataFX provides a Plugin for remote EJBs. By using the plugin you can inject a Remote-EJB-Proxy in your controller:

In this case the EJB Wrapper / Proxy will be injected by using the custom / plugin annotation

If you want to now more you should have a look at the DataFX tutorials or ask me :)

A short introduction to Bower

Some weeks ago I blogged about web components. Since that post I did a lot of research about this topic and had a talk about web components at JFokus. I really like this new technology and therefore I plan to blog about it more often in future. All the JavaFX lovers and readers of my blog shouldn’t be afraid. I will continue work with JavaFX ;)

Before going deep in the web components topic I want to introduce a tool that I think is needed when working with this new technology: bower.
bower-logo
Bower is an open source tool that is created by Twitter and helps you to manage the dependencies of a web application. By using bower you can define all the dependencies of your application and automatically download them.

Getting started with bower

Bower can be installed by using NPM and once it’s on your system you can create a bower configuration for your project by simply calling "bower init". By doing so you need to define some metadata for your project and bower will create a json file (bower.json) in your project folder. This file contains the definition of your project and might look like this:

Developers who are familiar with Maven might notice some parallels. Once the file is created you can add dependencies to your project by calling a bower command like "bower install --save webcomponentsjs" that installs the web components polyfill (I plan to blog later about that module). When looking at the bower file you will find a dependencies section that contains the added module. In addition a “bower_components” folder was created in your project that contains the defined dependency. Once this is done you can simply use any content of the “bower_components” folder in your application. But don’t forget to add the “bower_components” folder to .gitignore ;) When checking out the project from git you only need to call “bower install” and the cool little tool will download all the defined dependencies for you and add them to the “bower_components” folder automatically. So from a Java developer point of view this is mostly what Maven does for my Java project.

Here is a quick overview about the commands that is part of my JFokus talk:
bowe-ovwev

How to define dependencies

Some of you might ask yourself how you should know the definition or name of a dependency. Bower is more flexible that Maven in this case. When calling the "install" command there are different ways how a dependency can be specified. Here is a short overview that is taken from the bower web page:
bower install

In addition bower provides a search frontend (like the Maven central frontend) that can be used to search for modules and dependencies.

JSR377 got green light to continue!

Today the Review Ballot Results for JSR377 (Desktop|Embedded Application API) were published. As you can see the JSR was well received:

votesSpec lead Andres Almiray published the official web page for the JSR today.
If you want to know more about JSR377 you should read this introduction or have a look at the mailing list.

How to test your JavaFX application

Sven Ruppert and I gave a talk about Testing for JavaFX at Coding Serbia. In this talk we show how you can test your JavaFX application by using TestFX and describe some patterns that are very useful when testing big applications. A detailed blog post about the topic of the talk can be found here. The talk was recorded and published at YouTube:

Concurrency in UI Toolkits (Part 2)

In the first post of this series I showed how Concurrency is handled in UI Toolkits and how a generic approach to work with the toolkit specific thread may look like. This ends in the following interface:

But there are still some problems with this interface:

  • What happens if the runOnUiToolkitThreadAndWait(..) method is called on the UI-Thread?
  • One method returns a Future<> that defines the “boolean cancel(boolean mayInterruptIfRunning)” method. By definition thy method will interrupt the thread in that the task is running. But we never want to interrupt the UI Toolkit thread.

Let’s start with the first problem. Before we can solve this another question must be answered: I it’s a problem to call this methods on the toolkit thread we need a way to check if the current thread is the toolkit thread. To do so most toolkits provide a helper method that checks if the current thread is the toolkit Thread. Examples are shown in the following code snippet.

Because most Toolkits support this method we can simply add it to our interface:

Once this is done we can have a deeper look at the methods that will block until a task was executed on the ui toolkit. In the defined interface the two methods that are named “runOnUiToolkitThreadAndWait” defines this behavior. Once the method is called a new task is created and added to the ui thread. Because the thread has a lot of work to do normally a queue will handle this tasks and execute them by using a first in first out approach. The following image shows an example.

queue

By doing so our task will be added to the queue and executed once all task that has been added earlier to the queue were executed. If we call this method from the ui thread the created task can’t be executed before the task that is currently running is finished. But because the “runOnUiToolkitThreadAndWait” methods will wait for the execution of the new task we will end in an deadlock that is definitely the worst think that can happen. By doing so nothing can be handled on the UI thread: No user interaction or rendering can be done and the application is frozen. Because no Exception will be thrown the application just hangs we will receive no information what has triggered the error.
With the help of the new “isUIToolkitThread()” method we can avoid this behavior and refactor the methods to an more fail-safe version. With a simple if-statement we can add a special behavior if the “runOnUiToolkitThreadAndWait” method is called from the ui thread:

Once this is done we need to decide what we want to do if the method was called join the ui thread. In general there are two different ways how this is handled by ui toolkits:

  • throw an Exception (checked or unchecked)
  • directly execute the runnable by calling the run() method

Here are the implementations for this approaches:

The first 2 methods looks mostly the same. Only the exception type is different. The first method uses an unchecked exception that will end in a more readable code when using the method because you don’t need to catch the new exception type all the time. But developers need to know that an unchecked exception will be thrown whenever the method is called on the ui thread to avoid errors at runtime.
The third method can be called on any thread. A developer doesn’t need to think about it. If you know what you do, this is the most flexibel way how such a method can be defined. But on the other hand this can cause problems. I have seen a lot of projects where developers used this type of method way to often. Because they ad no idea how to handle the ui thread invokeAndWait(..) methods were called all over the code. By doing so your stack trace ends in something like this:

stack

This will end in code that is unperformant, unstable and can’t be maintained anymore. Therefore I would choose one of the first 2 implementations. But that’s only how I see this things and maybe you have a complete different opinion. Therefore it would be great if you can leave a comment here about your favorite way how to handle this problems. JSR-377 will contain such a interface and we want to resolve all the shown problems in an ui toolkit independent way. If you are interested in the JSR or want to share your opinion about this topic you should have a look at the JSR Mailing List. In the next post I will have a deeper look at the Future<> interface in combination with ui threads.

An introduction to Open Dolphin

Last year I started to work at Canoo and some of you might know that Canoo provides the open source remoting middleware Open Dolphin. At the end of the last year I had the pleasure to work with Open Dolphin in a customer project. Based on the experience of this project I started to contribute to Open Dolphin because I think that it provides an interesting way to handle the remoting aspects of an application. In addition I will blog about Open Dolphin and how you can use it in (JavaFX) applications.

dheadt
If I need to describe Open Dolphin in just a few words I would say that it is a library that syncs presentation models between a server and one or many clients. If you haven’t seen such an approach before it’s maybe hard to understand. Therefore I will start with a basic introduction of the core concepts with this post.

newA

As you can see in the image the client and the server can access the same presentation model. Let’s think about the presentation model as any data model. There are some best practices what kind of data should be defined in a presentation model but first of all let us define this as a model with any data in it. Both the client and the server can read data from the model or edit data in the model. Open Dolphin will automatically sync the model between the server and the client. In addition Open Dolphin supports multiple clients and therefore a more correct diagram would look something like this:

sync
As you can see in the picture all the different clients don’t know each other and the sync between the presentation models in centralized by the server. If client A edits a value in the presentation model it will be synchronized with the server. Once the server has updated it’s own presentation model with the new value the server synchronizes this change with all other clients. By doing you can create applications that share exactly the same presentation model. The following video shows a short example:

While the sharing of the presentation model between several clients is a very cool feature and big benefit most of the time you need to synchronize a model only between the server and one client. Therefore the examples that will be shown in the following post will all use this approach. Once this workflow is completely described I will start to introduce the sync of several clients in future posts.

Benefits of using Open Dolphin and presentation models

One big benefit of Open Dolphin is its independence to UI Toolkits. By default Open Dolphin doesn’t depend on any toolkit like JavaFX, Swing or GWT. By using Open Dolphin you can use the same presentation model for JavaFX and Java Script clients, for example. When using some of the best practices that I will show in future posts a migration from one UI technology to another one will be more easy by using Open Dolphin. In addition the creation of an application that supports different client implementations (for example mobile, desktop and web) can be based on Open Dolphin. By doing so only the view of the clients will be different because Open Dolphin capsulate the controller logic and the data model.
Next to the support of different client technologies Open Dolphin is based on the presentation model pattern. By doing so it combines many best practices to create MVC, MVP or MVVM applications. The following graphic shows how the MVC can be implemented by using Open Dolphin:

dolphin-mvc

The presentation model

Let’s have a deeper look at the presentation models and how such a model is structured and managed in Open Dolphin. Each presentation model is defined by an unique id. In addition a presentation model can be specified by a type. Both values are defined as a string. Open Dolphin provides methods to find a specific presentation model by its id or all presentation models of a given type.

A presentation model contains a set of attributes and each attribute defines a value in the presentation model. Let’s have a look at the following example to describe how attributes can be defined:

attributes
In this example we have two different input fields and therefore we will define 2 different attributes:

  • An attributes that defines the name value
  • An attributes that defines the description value

To create Attributes the Dolphin interface contains some factory methods. The following code snippet shows how the Attributes can be created:

In the code a both attributes are created by defining the name of the attribute and an initial value. Once the attributes are created we can create a presentation model that will automatically synced between client and server:

Once this is done the presentation model is created an can will automatically be synced between client and server whenever anything in it will be changed. This will happen if the value of an attribute will be changed, for example:

Next to the name an Open Dolphin attribute is defined by a tag and a qualifier. As shown with the type of presentation models attributes can be found by using its tag, for example. Since these powerful features aren’t needed for a first simple application I will show them in a later post.

Server commands

Another important feature of Open Dolphin is the support of server commands. On server side command handlers can be registered for a specific command. Each command is defined by a unique name and can be called from client side.

command
By doing so you can trigger server commands from client side. In a server command the presentation models can be accessed and modified. By doing so you can define a save command for example. Once the command is triggered you can convert the current content of the presentation model into business entities and persist them in a database.

On server side the command handler can be registered by using a method of the ServerDolphin interface:

Once the command handler is registered it can be called from client side:

By doing so the command will be called on server side.

Basic interfaces

The 3 most important interfaces of Open Dolphin are Dolphin, PresentationModel and Attribute. All three interfaces are defined in the dolphin-core module. In addition to the core model Open Dolphin provides a module for the client and the server side. Each of this modules contains a specialization of the interfaces. The dolphin-client module contains the ClientDolphin, ClientPresentationModel and CLientAttribute interfaces that extend the base ones for example.

interfaces
By doing so you need only one dependency for the client and one dependency for the server to use open dolphin:

Conclusion

This post shows some of the core concepts of Open Dolphin. For developers that used REST or EJB as the removing layer of applications this is a complete new approach. Therefore it’s important to understand how Open Dolphin works before creating a first simple application based on this concepts. In my next Open Dolphin post I will show how a first “Hello World” application can be created.

How to set up a DataFX application

A lot of people start using DataFX in small projects without a build file and by doing so they sometimes use old builds. Because of that I will give you some hints how to setup a project that is using DataFX.

DataFX builds

Every stable DataFX build can be found at Maven Central. If you are new to Maven or Maven Central just open this link. On the page you will find all artifacts of DataFX. If you for example want to use DataFX core you can download the jar, sources and javadoc here.

maven central

Each DataFX artifact is defined by the group-id, artifact-id and version. The group-id is always “io.datafx” and the artifact-id depends on the DataFX-Module. If you for example want to create an application that is suing the DataFX Flow you need the datafx-flow module and all it’s dependencies. At the moment the last stable version is 8.0.

If you want to download the DataFX jars by hand and add them to your application you need to download all dependencies of the module, too. Thankfully DataFX doesn’t have much dependencies. Here is an overview:
datafx-dep.016

Once you have downloaded the last version of DataFX and added the jars to the class path of your application you can start coding.

Using builds tools

Normally you won’t download the dependencies of your application manually. Build tools like Maven or Gradle can do this job for you. By using one of the tools you only need to define the dependencies in your build file and the build tool will automatically download all needed jars. In addition the tools support transitive dependencies. This allows you to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically. If you Maven as build tool and you only want to add the DataFX Flow API to your application you only need to add one dependency:

Use DataFX in your application

Once you added DataFX as dependency to your application you can using it as described in the tutorials.

DataFX Tutorial 6

In this tutorial I want to show how dynamic actions can be handled in DataFX. In all the last tutorials the actions are defined in the flow configuration or by using annotations. By doing so you can’t dynamically choose which action should be called when clicking a button for example. To do so DataFX provides the FlowActionHandler class. This class provides methods to call DataFX actions directly in code. Here are some examples:

As you can see the FlowActionHandler class provides methods for all the action types that are supported in DataFX by using annotations or the flow configuration.
Normally you want to use the FlowActionHandler inside of a view to call dynamic actions based on a user interaction. To do so DataFX provides the @ActionHandler annotation that can be used to inject the FlowActionHandler in a view controller. Here is a small example how this will look:

As you can see it is really easy to call DataFX actions in code. As a next step we want to create a small application that uses this features.
Let’s say we have a main view and 3 sub views. In the main view you can choose by using radio buttons to which view you want to navigate.
mainview
To do so we create a controller with the “navigate” buttons and the radio buttons. As a next step we need to define a ToggleGroup for all the radio buttons. This group manages the RadioButton instances. By doing so you can only select one RadioButton. This is a JavaFX basic feature. If you want to now more about RadioButtons and ToggleGroups you should buy this book or visit this training. After this is done the controller should look like this:

As you can see in the code I don’t use the @FXML annotation. With DataFX 8 we introduced the @ViewNode annotation to inject components of the view in the controller. Basically this annotation can be used as the @FXML annotation but it provides more features. You can define the fx:id of the node as the value of the annotation, for example. By doing so your field must not have the same name as the node in the FXML file. Here is a short example how this can be used:

In addition the JSR-377 is currently planned and this will introduce a UI Toolkit independent annotation to inject view components. DataFX will implement the JSR once it is released and therefor we started to define our own basic annotations. SO maybe the name of the annotation will change once the JSR is released.
Once the controller is finished we need to add the action handler and navigate to the selected view. The RadioButtons instances in the controller define the controller classes for all the subviews as user data. By doing so we can simply navigate to the selected user data. Here is the final code for the controller:

Once this is done you can select the wanted view in the UI and by clicking the “navigate” button the view will change to the selected one.
nav
All the view controllers for the subviews are defined as shown in earlier tutorials. You can find the complete code of the example here.