Category Archives: Language

JavaFX Script and language related tips.

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

Updated! 4/2/2017 * The latest update of the JDK 9 updated the –module-path switch.

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.

Requirements

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

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

Instructions

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.

Java 9 early release build 162.

 

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>/
              helloworld/
                 src/
                    com.mycompany.helloworld/
                       com/
                          mycompany/
                             helloworld/

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.controls;
   exports com.mycompany.helloworld;
}

The module-info.java defined above used to have modules javafx.base and javafx.graphics, however thanks to Abhinay Agarwal who pointed out that they are transitive dependencies and don’t need to be added because they are already included when using the javafx.controls module.

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) {
       Application.launch(args);
    }

    @Override
    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.setLayoutX(100);
       btn.setLayoutY(80);
       btn.setText("Hello World");
       btn.setOnAction( actionEvent ->
                 System.out.println("Hello World"));
       root.getChildren().add(btn);
       stage.setScene(scene);
       stage.show();
    }
}

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 –module-path 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 --module-path 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

 

Conclusion

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.

References:

Project Jigsaw: Module System Quick-Start Guide: http://openjdk.java.net/projects/jigsaw/quick-start

Java Platform, Standard Edition Oracle JDK 9 Migration Guide: https://docs.oracle.com/javase/9/migrate/toc.htm

Project Jigsaw: http://blog.codefx.org/tag/project-jigsaw/

The State of the Module System: http://openjdk.java.net/projects/jigsaw/spec/sotms/

 

FX Playground

 

 

 

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

Logo5

Introduction

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.

 

Roadmap

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):

References

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 2.0 Introduction by Example book

I recently finished writing a book on the new release of the JavaFX 2.0 SDK and it has already been placed on the shelves at a bookstore (Amazon) near you. The book will walk you through, step-by-step, giving you the ins and outs of JavaFX 2.0. When you encounter a chapter you will be presented recipes which will pose a problem (use case scenario) that will have an associated solution. After a proposed solution you will be shown an example source code listing and its display output after the program has been executed. Lastly you will be shown a section called “How it works” which will explain and discuss the examples and their details. To see more about this book, such as the source code and errata, please visit Apress Publishing (http://www.apress.com/9781430242574).

In this blog entry I also want to give you a sneak preview of a Java Webstart example of chapter 3 recipe 3-1 (JavaFX 2.0 MP3 Player). To launch the JavaFX MP3 player just jump down to Chapter 3 below.

Below is a brief overview of the chapters in the book:

Chapter 1: JavaFX Fundamentals

I begin by instructing you on how to get your environment set-up to rapidly develop rich internet applications using Java and JavaFX.

JavaFX Swiss army knife

After reading this chapter you will be able to answer questions such as:

  • How do I create GUI applications?
  • What is the Scene graph?
  • How do I display text onto the scene graph?
  • How do I incorporate UI controls into my application?
  • How do I bind expressions?
  • How do I draw shapes?
  • How do I generate a background process?
  • How do I associate keyboard sequences to applications?

Chapter 2: Graphics with JavaFX
In chapter 2 there are recipe examples which delve into JavaFX’s graphics and animation capabilities. I begin by explaining some of the basics of JavaFX’s Graphics such as rendering images and animating nodes. I then go on to more advanced topics such as animating with transitions, manipulating layouts, and enhancing nodes using JavaFX CSS.
The following picture, taken from Recipe 2-2, depicts an image viewer application with a custom news ticker control at the bottom.

Photo Viewer and News Ticker application

Photo Viewer and News Ticker application

Chapter 3: Media with JavaFX
Chapter 3 covers all things media related. Here I reveal JavaFX’s media APIs which allows you to integrate audio and video into your applications. I begin by showing you how to create a JavaFX MP3 player and a video player. Then I will walk you through the different ways to enhance the video player with additional features to control media actions and events, mark positions in a video, and synchronize animations.

The illustration below, taken from Recipe 3-1, depicts a JavaFX 2.0 MP3 player with a graphical visualization (using the AudioSpectrumListener API). Before launching the example you will need to know the requirements and instructions to run the demo example.

JavaFX 2.0 MP3 Player

JavaFX MP3 Player

Simple requirements and instructions to run the JavaFX 2.0 MP3 Player:

Requirements

  • Java 6 update 24 JRE or greater (Java 7 is preferred)
  • JavaFX 2.0 or greater (JavaFX 2.0.2 is preferred)
  • Windows XP SP 3 or greater. (I will update the jnlp as JavaFX becomes available on other OSes)

Instructions

  1. Click the Webstart launch button below.
  2. By using your file explorer on your host operating system “drag and drop” a music mp3 file onto the surface of the application.
  3. Use the controls to the bottom right of the application to pause, play, and stop the music.
  4. You may use your mouse to drag the application around your desktop.
  5. To close the application click on the ‘X’ in the upper right hand corner.

To launch the application click on the Java Webstart button below:

Demo JavaFX 2.0 MP3 Player

Chapter 4: JavaFX on the Web
In chapter 4 you will be able to take advantage of the interoperability between JavaFX and HTML5.

For starters I will cover how to embed JavaFX applications into a Web page. I then will demonstrate JavaFX’s powerful WebView and WebEngine APIs. Below are the recipe examples from chapter 4 which utilize the  WebView and WebEngine APIs:

  • Displaying HTML5 Content (animated analog clock application)
  • Loading data from a Web service (weather application)
  • Handling Web events
  • Storing and displaying data using an embedded database (RSS reader application)

Depicted below is an animated analog clock application, taken from Recipe 4-2, demonstrating the ability to render HTML5 content.

JavaFX 2.0 Analog Clock

JavaFX 2.0 Analog Clock (HTML5)

I assume you know the Java programming language and some web development concepts. I hope you will enjoy these examples which can be used freely in your own projects. I’ve tested the examples with the latest Java 7 update 2 and JavaFX 2.0.2 runtime and SDK. If you have any questions or comments feel free to ask them here or on my Twitter account @carldea .

Thanks!

Carl

JavaFX 2.0 Roadmap

Road to tommorow

Road to Tomorrow

In case folks did not notice the JavaFX Script Language has been converted to pure Java APIs for JavaFX 2.0. I’ve recently been fortunate to be able to take things out for a spin (JavaFX 2.0 EA). To my surprise I am very impressed by the work of the JavaFX teams and the amount that had been done so far. In a little over a four month period, they have managed to take on most if not all the features from 1.0 to 1.3.x, added many new controls and increased performance. Kudos Guys and Gals at Oracle!

There is much more to do and if you want to help out please be on the look out for JavaFX 2.0 Beta release and then head on over to http://javafx-jira.kenai.com for tracking bugs and features. To see what tomorrow brings for JavaFX here is the official Roadmap: http://javafx.com/roadmap/

I believe the road to the Java Desktop is getting brighter again.

JavaFX – Java Applets Making a Comeback?

Pedal to the metal

Petal to the metal

Introduction

In 2008 JavaWorld had written a great article by Jeff Friesen called “Are applets making a comeback?“. Jeff Friesen poses this question to leading thinkers and doers in the Java developer community. Although the question posed to readers may seem rhetorical, and difficult to answer with an emphatic “Yes“.  I want to try to answer this question in the year 2010.  Right after Oracle has finalized its acquisition of Sun Microsystems, Larry Ellison CEO of Oracle had  an Oracle + Sun Product Strategy Webcast announcing it would invest heavily in JavaFX. So, currently there are lots of things going on with the JavaFX platform. As the JavaFX platform matures the community should mature. So, hopefully I can encourage you to stay more involved in helping the JavaFX community grow.

Are Applets Making a Comeback?

Many Java Developers who have used Applets in the past, have often felt inadequate when competing with the new Web Order due to all the AJAX and Adobe Flash craze.  One of the main complaints about Java Applets was its start-up time. In my opinion ‘Perception‘ is key and when it comes to user experience, it is often said that “If it looks and feels slow, the application is probably not worth running“.  I believe that our society has this urge of instant gratification, so being patient is a hard thing to do these days. During years past Java developers have been longing for that day when Java Applets will make its big comeback. While many Sun engineers are working tirelessly solving this problem it always seems on going (It should).  Sometimes I’ll come across Java developers still feeling unconvinced whenever an update is released. I also have heard people get quite flustered and a little threatening.  I don’t mind if you complain, but do something about it. Then some will say, “What can I do about it?“. Well, the obvious things are forums, blogs and filing bugs. I normally am an early adopter when it comes to Java/JavaFX updates relating to performance increases. Just like folks who decide to buy a new game (Like StarCraft 2) off the shelf they’ll take a look at the graphics requirements such as video ram, etc in hopes their computer can handle it. If not they will likely upgrade their video card or buy a new computer all together. So, upgrading your Java Runtime Environment (JRE) is a snap. So, you are probably wondering where is the part where I encourage you? Well, let me just say with the recent release of JRE 1.6 update 18, I was pretty impressed  with the start-up and reload performance increases. To really see how fast Applets start-up I recommend installing the latest JRE (1.6 update 18), and to please visit Oracle/Sun engineer Rakesh Menon‘s blog entry called “JavaFX – Applet Startup Time“. On his site you will see a list of many folks taking some time to record metrics and describing their browser, OS, and hardware (Please note: make sure your Java Console is set to display so that a text dump outputting  the metrics can later be cut and pasted). I also suggest posting your results if you have a different configuration than the others on the list.

*Note: When clearing the cache (from the Java Control Panel) while having Firefox open be sure to restart Firefox or close tab before re-running the applet.

Conclusion

Once you will notice the start-up time increased you should be able to answer the question yourself  “Are Applets Making a Comeback?“. I know I can see the difference and I’m sure you will too. The Java/JavaFX community with tons of libraries and very good boosts in performance, I truly believe it is safe to say with an emphatic “Yes, Applets are making a comeback!”.  I also want to mention about two very cool sites to test drive your new JRE w/start-up/reload enhanced:

Lastly, I want to applaud and thank the Java/JavaFX engineers (Rakesh and company) for making these great strides.

References

Are applets making a comeback? by Jeff Friesen: http://www.javaworld.com/javaworld/jw-05-2008/jw-05-applets.html
Larry Ellison CEO of Oracle: http://en.wikipedia.org/wiki/Larry_Ellison
Interactive Pulp – JavaFX, startup time, and security dialogs : http://www.interactivepulp.com/blog/2008/12/javafx-startup-time-and-security-dialogs
Oracle invests in JavaFX: http://learnjavafx.typepad.com/weblog/2010/01/oracle-we-will-invest-heavily-in-javafx.html
Oracle/Sun strategy Webcast: http://www.oracle.com/events/productstrategy/index.html
New Applet Experience by Jeff Friesen: http://www.javaworld.com/javaworld/jw-05-2008/jw-05-newapplet.html
JavaFX forums: http://forums.sun.com/category.jspa?categoryID=132
The JavaFX Journey filing bugs: http://piliq.com/javafx/?p=1144
The Vancouver 2010 Olympics: http://www.vancouver2010.com/olympic-medals/geo-view/
JavaFX – Applet Startup Time: http://rakeshmenonp.wordpress.com/2009/08/31/javafx-applet-startup-time/
Star Cannon: http://www.freearcade.com/StarCannon.jav/StarCannon.html

JavaFX Forms Framework Part 2

Full Name Form with Validation

Full Name Form with Validation

Introduction

This is the second installment of a series of blog entries relating to a proof of concept for a JavaFX Forms Framework. Before I specify the requirements and a simple design of the FXForms Framework, I want to follow-up on comments about tough issues relating to enterprise application development and JavaFX. If you recall in Part 1 we discussed about MVC form based technologies. I listed many technologies that may only provide a means to separate content from presentation, but they don’t necessarily deal with real plumbing problems such as Threading, Binding, Validation and Transactions.  I believe these issues are one of the most important areas that must be understood in the JavaFX world, thus positioning itself as a premiere enterprise development platform (not just rich client a hint to Oracle).  As Richard Obaldeston mentions in the comments regarding enterprise level support for JavaFX controls similar to Swinglabs / SwingX. I cannot speak of the future concerning Swing & Swinglabs, but I believe the JavaFX teams are well aware of them, (very much so) due to the fact that the same project owners of the SwingX-WS are leads on the JavaFX teams (I don’t mean to put them on the spot).  Many of these difficult issues are mostly solved in the Browser based Web Application Development world and can also be done in the JavaFX world (Check out Exadel). Of course I can’t answer all the hurdles faced in just one blog entry especially because every enterprise application has varied types of architectures such as (Corba, RMI, EJB, Soap, RESTful, JSON, Jini, JMS, DAO, JDO, JDBC, JNI, etc). It would literally take a book or two. But, I will try to address some of them later in this blog as we discuss JavaFX and Java interoperability. One should always re-evaluate one’s architecture to adhere to best practices or industry standards and conventions. However, some standards seem to stall or are slow to be accepted (JSR-296 or JSR-295) with many reasons of course. It is often the nature of the beast when it comes to new technology solutions and refactoring that subsequently boils down to when and how you want to pick your battles. As readers of this blog for the first time who might be new to JavaFX or Java Swing I strongly encouraged you to explore and learn about the pitfalls of thread safety, asynchronous behaviors, best practices, and UI concepts like (UI blocking, disabling, progress bar, etc.) . So, let’s get started with requirements and the analysis phase of our FXForms Framework.

Requirements

My main goal of these series of blog entries are to share with others my experience with creating an application called iSF86 which hopefully will end up in the Java App Store and make tons of cash so I can quit my day job like Ethan (wishful thinking). iSF86 is an application which contains many form elements to capture a person’s information to apply for a job doing classified work for the United States Government. When dealing with so many forms I thought of building a mini Forms Framework where domain objects can be mapped to forms. The application will save a person’s SF86 information locally as an XML file. This is purely a client-side application which doesn’t involve any server-side communications. Each form would be bound to domain objects in a bi-directional way. A domain object that is bound to an existing form can be swapped out with a different domain object, thus making the old bean ready to be garbage collected and unbound to the form. Important Note: One requirement is that the domain objects will be JavaBeans (see disclaimer below).

Disclaimer: For brevity, the requirements are for JavaBeans (change support) and not POJOs (there is a difference)! Yes, I know I said POJOs in Part 1, because I wanted to tackle the problem using byte code engineering for boiler plate code for property change support on POJOs, but it would be beyond the scope of the blog series’ goal. So, this tutorial is really geared for people migrating Swing/SWT applications to JavaFX applications.

FX Forms Framework Requirements:

  1. It shall bind JavaFX Forms to JavaBeans as domain objects
  2. It shall enable JavaBeans to be swapped in a JavaFX Form
  3. It shall provide validation on property values
  4. It shall provide Action bindings to controls

To keep the framework simple shown below is a list of features that the framework does not provide.  Interesting features will later be discussed in Part 4 Enhancements.

What the FX Forms Framework does NOT provide:

  • Application Framework Features (like JSR-296)
    • Application Lifecycle
    • Resource injection
    • Task Monitoring
    • Saved Preferences
    • Thread Pool
  • Forms Building
  • RCP Features
    • Window Docking
    • Menu bar
    • Etc.

Design

Before going into the design I want to mention other technologies which provide beans to forms binding or RIA MVC capable. The mentioned technologies are primarily Java based. Some of my classes will use similar names because I’ve taken a lot of ideas from these frameworks in the past.  Here are just a few that come to mind:

As a reminder regarding rapid application development that there are two main areas on building applications quickly ‘Forms building’ and ‘Forms binding’. We will only focus on ‘Forms binding’. Ok, already! Let’s get to the designing.

User of the API

At times when it comes to API development I’m a fan of user driven design and the user of the API is who I’m targeting. So, I pretend the FXForms Framework is ready to be used. Below is the developer obtaining a JavaBean and setting it into some Form.

// normally loaded from external source
var personBean1:PersonBean = new PersonBean(); // change support enabled
personBean1.setFirstName("SpongeBob");
.
.
.

// generate a form and bind to bean. Req #1
var personForm:NameForm = NameForm{
jBean:personBean1
};

// subsequent time another domain object is loaded Req #2
var personBean2:PersonBean = … // loaded from external source.
personForm.jBean = personBean2; // old person bean is no longer attached

// set property to an invalid value. Req #3
personBean2.setFirstName(“#$”);
// validator will fire to output error message

// create navigation panel area Req #4
var mainButtonForm:PresentationModel = MainButtonForm {
jBean:personBean2
};
var nextButton:Button = mainButtonForm.getControl(‘nextButton’);
// simulate a mouse press to test action binding

Let’s step through the code to see what is happening and what the FXForms Framework will provide.

Line 1: Creating domain object or loading from external source. Notice the new on the PersonBean (Java Object).

Line 8: Instantiating a Form to use the current JavaBean loaded. All the properties will be bound to form elements bi-directionally. Changes in the GUI will affect properties and changes to the bean properties will change the GUI fields. (Requirement #1)

Line 14: Swapping a domain object with the existing form. Old bean is disconnected from the form and replaced with new bean. Presentation Model Pattern (Requirement #2)

Line 17: Validation of a property when set with invalid data. The user can type into the textbox to fire the validator code. ValueModel updated (Requirement #3)

Line 20-25: A button panel form has buttons mapped to actions. Command Pattern. Yes, this is strange but I will explain later. (Requirement #4)

You will notice the comment on line 25 where you could test a control such as obtaining a button independent of the application being launched (testing individual forms).  This brings up a good point when using MVC Frameworks.  In  the Swing world I highly recommend using FEST Swing a tool to test Swing applications with ease. Also, the team is working on FEST for JavaFX with a joint effort with the JFXtras team.

JavaFX and Java Interoperability

While the user of the API appears simple, it is the behind-the-scenes work that some may consider unorthodox when using a combination of Triggers, Bindings, Reflection, Threading, etc. Until the JavaFX teams expose (with JavaFX blessed code) better interoperability against Java and JavaFX, I will resort to techniques that are known and official. When using triggers on properties this enables us to follow the basic proxy pattern: where a property is changed you will have an opportunity to intercept the change and update value models, which also updates GUI widgets mapped to them. One concern is that object-based memory leaks could occur with inverse bind (Maybe we need a unbind keyword). Another problem is properly populating a form on or off the JavaFX’s main process thread (EDT on the desktop environment) without blocking the GUI thread or causing some race condition.  What follows are the necessary classes to implement the FXForms framework.

Class Design

// Java
DomainModel <abstract Java class>
pcs:PropertyChangeSupport

// Java
PersonBean extends DomainModel <JavaBean>
firstName:String
middleName:String
lastName:String
suffixName:String

// JavaFX
FieldSetter <mixin class> Adapter
valueModel:ValueModel
boundValue:String

// JavaFX
MyTextBox extends TextBox, FieldSetter
updateField(obj:Object):Void

// JavaFX
ValueModel <adapter class>
propertyName:String
guiControls:FieldSetter[]
boundValue:Object
jBean:Object

// JavaFX
PresentationModel extends PropertyChangeListener <mixin class>
propertyValues: Map <String, ValueModel>
propertyValidatorMap: Map <String, List<Validator>
jBean: DomainModel // java class javabean inherit
getModel(propertyName:String):ValueModel
getControl(propertyName:String):Control
propertyChange(changeEvent: PropertyChangeEvent):Void

//JavaFX
Form
guiControls:[] // Scene.lookup(id) is currently a bug in jfx 1.2
presentationModel:PresentationModel

// JavaFX
NameForm extends CustomNode, Form, PresentationModel <JavaFX node>

// JavaFX
Validator
validate():ValidationResult

// JavaFX
ValidationResult
messages:[]
getMessages():Message

// JavaFX
Message

key:String
propertyName:String
errorType:[“warn”,”err”]
text:String

You will notice the NameForm inherits the PresentationModel mixin class which provides the controller functionality mixed in with the view. I’ve done this to make the example short Sometimes I’m not a big fan of inheritance especially in this case and decided to refactor in order to separate the “Presentation Model” from the “View Form” for form reuse.  There are situations such as reusing the same GUI form for “Adding” and “Editing“, but the validation of the form data is different. Developers may also create a concrete presentation model that inherits from the mixin class to be independent of the view so that it decouples the Form and the Presentation Model. An EditPresentationModel and an AddPresentationModel should be created to have two different validations using the same GUI form.  Again for a slim down version I’ve omitted the ability to consume an XML file detailing the form metadata and mappings such as actions, mandatory fields, validators, and custom bindings; the named property is the same name as the ‘id’ attribute on the JavaFX GUI form element (TextBox). I will discuss in Part 4 Enhancements. Relating to validation at some point I would like to provide a way to display warnings and error icons beside fields whenever a Validation Result is updated. The validation results will contain the error messages to be displayed. One last thing to mention is GUI component factories aren’t in the design. You will also notice when creating a TextBox I needed additional behavior, so I simply created a MyTextBox instead of something like var field1 = WidgetFactory.create(valueModel, “TextBox”) to wrap, return and put it into form.

Conclusion

This is surely not a thorough or complete design, but an attempt to demonstrate how to make a simple forms framework from scratch. Hopefully, I’ve captured the requirements and articulated the object relationships within the textual design (No UML sorry). Next, we will look into how to implement the FXForms Framework in Part 3. Please be advised that this design is subject to change as any development shop would.

Personal Note: Sometimes I wonder if Sun had focused on finishing the often highly controversial JSR 295 Beans Binding and Java Properties before JavaFX would it render this blog entry totally useless.

Any comments are welcome. Thanks!

-Carl

References

JavaFX w/JMS 307-311 JavaFX RIA book Server Call Back- James Clarke updates code for JavaFX – Developing RIA book regarding Code Recipe for JMS pages 307-3011 http://tinyurl.com/lzej5x

Best practices: http://www.greggbolinger.com/blog/2008/11/11/1226423940000.html

Fuse http://weblogs.java.net/blog/joconner/archive/2007/11/index.html

Exadel, http://mkblog.exadel.com/ria/javafx-and-spring-crud/

Swing worker / swing/ http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html

Beans Binding: https://beansbinding.dev.java.net/

RESTful : http://jnb.ociweb.com/jnb/jnbAug2009.html

jfxtras JFXWorker http://jfxtras.googlecode.com/svn/site/javadoc/release-0.5/org.jfxtras.async/org.jfxtras.async.JFXWorker.html

Java Properties: http://tech.puredanger.com/java7#property

Fxbuilder: http://www.jroller.com/aalmiray/entry/griffon_gfxbuilder_fxbuilder_side_by

Disable Swing Container:http://weblogs.java.net/blog/alexfromsun/archive/2007/06/_enablingdisabl_1.html

Java Properties without Getters and Setters: http://www.artima.com/forums/flat.jsp?forum=270&thread=247837

Beans Binding (JSR 295) & Properties on JDK7: http://www.javalobby.org/java/forums/t101998.html

JSR 295: http://jcp.org/en/jsr/detail?id=295

RCP Spring rich- http://spring-rich-c.sourceforge.net/1.0.0/index.html

SAF:https://appframework.dev.java.net/intro/index.html

Oracle buys Sun : http://www.oracle.com/us/corporate/press/018363

JFXtras Community Site

JFXtras Community Site

Stephen Chin a co-author of Pro JavaFX Platform has created a new community site dedicated to JavaFX called JFXtras Community Site. Here you will discuss, develop and help extend the JavaFX platform. Just register to be a member and enjoy the benefits on being part of growing the JavaFX community!

JFXtras Core –  Utilities and Add-ons for JavaFX
JFXtras Test –  Declarative UI and Unit Testing
JFXtras SamplesOpen Source and Tutorials and Examples
JFXtras LinksWeekly Community Links