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

JavaFX Strings vs Java Strings

Introduction

Assateague Island Pony

Assateague Island Pony

One of the first things we learn in any language is outputting text such as “Hello World“. Most languages support strings (unlike C’s char array) which makes storing and outputting text easy, however dealing with strings was often painful from one language to another. I will contrast between JavaFX Strings and Java Strings to help demonstrate how using them will make your pains disappear!

High level issues that many languages encounter with Strings:

  • Readability – Difficult to read when string literals are large
  • Expressions – Embedded expressions in strings.
  • Formatting – Formatting objects into strings

Example 1 – Readability

Often folks who have worked with JEE Web apps has one time or another has hand written JDBC code using SQL statements to run against a database. And if you have used the Java Persistence API (JPA), I’m sure you have written a named query at least once. Have you ever noticed the ugliness of string concatenation?

[Disclaimer: There are plenty of object relational persistent APIs that don’t like hand built SQLs or Bean managed persistence. Just pretend you are learning JDBC for the very first time. I’m not responsible for SQL injection hacks, so please don’t use the code below in a production system.]

Here is a Java String literal containing a SQL statement:

// Java Code
String param1 = "Carl";
String sql = "SELECT " +
                      "EMP.fname, " +
                      "EMP.lname " +
                  "FROM " +
                      "EMP " +
                  "WHERE " +
                      "EMP.fname LIKE '" + param1 + "'%";

Now let’s see how it looks in JavaFX:

// JavaFX Code
def param1 = "Carl";
var sql = "SELECT "
             "EMP.fname,"
             "EMP.lname "
          "FROM "
             "EMP "
          "WHERE "
             "EMP.fname LIKE '{param1}'%";

Note: You will notice the SQL statement has less clutter and the param1 expression is inside the last part of the where clause. Eazy peazy! The next example will be a more elaborate expression that is embedded in a string.

Example 2 – Expressions

// Java Code
public void outputTruth(boolean news) {
      //String reportNews = news ? "is":"is not"; // tiny bit cryptic
      String reportNews = null;
      if (news)
          reportNews = "is"
      else
          reportNews = "is not";
      System.out.println("The news " + reportNews + " trustworthy");
}

Let’s see the JavaFX-cellent implementation:

// JavaFX Code
public function outputTruth(news:Boolean) {
      println("The news {if (news) "is" else "is not"} trustworthy");
}

Note: An embedded expression within the curly braces will return a string object. A good rule of thumb is to keep the expressions simple.

Example 3 – Formatting

To format an String value you must first create a format object. Remember a Java java.text.Format object is not thread safe. Synchronize it or create another one.

// Java Code
Format dateFormat = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(new Date());
System.out.println(s);

Here is the JavaFX equivalent:

// JavaFX Code
var s = "{%MM/dd/yy java.util.Date{}}";
println(s);

Note: After the ‘%’ is the format specified as ‘MM/dd/yy’ then a SPACE and then the object to be formatted (Date object). To see the format pattern letters take a look at the Java Doc for SimpleDateFormat.

Conclusion

Strings in JavaFX are extremely easy to use and definitely less typing. The added clarity will help people debug better. So, Happy stringing!  Let me know what you think. Any feedback is always welcome.

Does JavaFX have Multiple Inheritance?

CatDog cartoon from Nickodean

CatDog cartoon from Nickelodeon

Introduction

Often when we learn about object oriented programming we try to find out if a particular language contains a dirty little phrase called multiple inheritance. Of course there are good reasons to try to avoid it (Diamond Problem) but sometimes you can’t.  I believe that it can be used in certain contexts which can be done safely (fearing and trembling from angry purists). In Java when asked if multiple inheritance is supported the answer is “Well, Sort of” or “Yes, but…“. Java has interfaces which follows the Design by Contract concept which forces the developer to implement the interface methods. Fundamentally when we think of abstraction we think of what behavior is common across classes. Abstract classes help but tend to get bloated and some folks resort to creating NOP (No operation performed) methods. One of the major principles of object oriented programming is re-use not un-re-use while rendering an object very coupled-ygoop. It would be wonderful if you could have method re-use from an abstract data type. Well, JavaFX has this ability to do this very thing! So, to ask the question again “Does JavaFX have multiple inheritance?“. I would answer it like this: “Yes, its similar to Java’s Interfaces but with implementation details“. JavaFX uses a concept called Mixin classes which allows the developer to inherit multiple classes. Sweet!

Example

I couldn’t help but think about all kinds of cats when thinking about multiple inheritance (not to be confused with these types of cats I Can Has Cheezburger ). In a nutshell there are Big cats and Small cats.

Requirements:

  • Some Big cats can roar, but all big cats can’t meow.
  • Similarly small cats can meow, but all small cats can’t roar.
  • All cats can purr.

In this example we will model reusable behavior as Mixins and we will also create the standard abstract classes such as “Animal” and “Cat“.

Step 1: Create Abstract Classes

abstract class Animal {
    public var name:String;
    public function eat(food:String){
        println("munchin on {food}");
    }
}

abstract public class Cat extends Animal {
    public function purr(volume:Integer){
        println("Purrrr...level({volume})");
    }
    public function scratch(){
        println("Scratching...")
    }

}

Step 2: Create Mixin Classes

public mixin class Roarer {
    public var bass:Integer = 20;
    public function roar(){
        println("Roar...");
    }
}

public mixin class Meower {
    public var pitch:Integer = 5;
    public function meow(){
        println("Meow...");
    }
}

Step 3: Create Derived Classes Inheriting Mixin Classes

// Cheetah's can't roar and can't meow
class Cheetah extends Cat {
}

class Lion extends Cat, Roarer{
    public override var bass = 50;
    public override function roar() {
        println("(ROAR) I'm King of the land!!!");
    }
}

class HouseCat extends Cat, Meower {
    public override var pitch = 10;
    public override function meow(){
        println("Meow...");
    }
}

Step 4: Create instances of the types of Cats

var fluffy:Cat = HouseCat{name:'fluffy'}; // regular house cat
var simba:Cat = Lion{name:'Simba'};      // Lion King cat
var chester:Cat = Cheetah{name:'Chester'}; // Cheetos' Chester

var cats:Cat[] = [fluffy, simba, chester]; // cat bus

Step 5: Create a script level function

Cat will ask to come into your house. Notice the down cast to Meower and Roarer type cats.

function letMeIntoHouse(cat:Cat){
        print("LET ME IN! ");
        if (cat instanceof Meower){
            var meower = (cat as Meower);
            meower.meow();
        }
        if (cat instanceof Roarer){
            var roarer = (cat as Roarer);
            roarer.roar();
        }
        cat.scratch();
}

Step 6: run() function like Java’s main()

This will loop through a sequence of cats by:

  • Cat asking in your house
  • Introduces cat
  • Feeds cat
  • Cat will purr
  • function run(){
        def food:String = "tender vittles";
        for (cat:Cat in cats){
            letMeIntoHouse(cat);
            print("The cat named {cat.name} is ");
            cat.eat(food);
            cat.purr(5);
        }
    }

    Output

    LET ME IN! Meow...
    Scratching...
    The cat named fluffy is munchin on tender vittles
    Purrrr...level(5)
    LET ME IN! (ROAR) I'm King of the land!!!
    Scratching...
    The cat named Simba is munchin on tender vittles
    Purrrr...level(5)
    LET ME IN! Scratching...
    The cat named Chester is munchin on tender vittles
    Purrrr...level(5)

    Conclusion

    Although this example doesn’t use Mixins in an RIA context, instead its used with simple domain objects to show multiple inheritance. Hopefully we can now answer the question when asked, “Does JavaFX have multiple inheritance?“. Is it ever a quick answer?

    References:

    JavaFX Presentation Model Pattern Using Binding

    Introduction

    When working with Java Swing I used the JGoodies libraries such as Binding, Forms, Validation to build very cool Swing applications. So, this enabled me to soon learn the Presentation Pattern. The key advantages using the presentation pattern are to decouple the domain objects from the presentation layer, to help reduce complexity and facilitate multiple presentation layers. Some other advantages are ease of unit testing, functional testing (testing various layers independently of each other) and code maintenance (better package structuring).  Since JavaFX has binding for fweee (a line in the movie Bed Time Stories) do we still need to be concerned or understand this great pattern while using JavaFX? I believe we should. In my opinion I think people would likely get into trouble with the bind keyword without proper understanding of the presentation model pattern. Here I will demonstrate a simple form with a TextBox bound to a domain object in a bidirectional way. (written using JavaFX 1.2)

    Example

    There are two scenarios that will describe how data will flow. Scenario 1 is when a user is changing information on the view component and the data will be set on the domain object. Scenario 2 is when data is set in a domain object which intern will update the view component. In the application there will be a section called Variables which will display each variable or attribute being set.

    Scenario 1: Changing the View

    Enter Person Name

    Enter Person Name

    A GUI form contains a field allowing the user to type in the person’s name. As soon as the user loses focus or hits the Enter key the person object’s name is automatically populated.


    Scenario 2: Changing the Model

    Setting bean property

    Setting bean property

    A GUI form contains a second field allowing the user to type in the person’s name. As soon as the user hits the Enter key the person object’s name property will be modified which notifies the presentation model which updates the view (TextBox) component with the new name (text property).

    Presentation Model Pattern Demo – This is a simple test to demonstrate how we can mimic the presentation model pattern. Click image to launch.

    Presentation Model Pattern Demo

    Presentation Model Pattern Demo

    Step 1: Create domain object

    //Simple JavaFX bean class
    class Person {
        public var name:String
    }

    Step 2: Create presentation model

    // create presentation model
    var namePresentationModel:String on replace oldValue {
        println("Old Value = {oldValue}"); // debug code
        println("New Value = {namePresentationModel}"); // debug code
    }

    Step 3: Create a person object instance from the Person class
    By binding the presentation model with the person object’s name attribute and using inverse to bind the other way. Person.name notifies namePresentationModel which notifies personForm (TextBox see Step 4)

    // create an object instance of Person
    var personBean = Person{
        name: bind namePresentationModel with inverse
    };

    Step 4: Create view component (Person’s name TextBox)

    By binding the presentation model with the personForm(TextBox) ‘s text attribute and using inverse to bind the other way. personForm (TextBox) notifies namePresentationModel which notifies Person.name. This is a JavaFX common profile TextBox component.

    // create the view or form (in this case just a textbox)
    // bidirectional binding to presentation model
    var personForm:TextBox = TextBox{
                    text: bind namePresentationModel with inverse
                    columns: 12
                    selectOnFocus: true
    }

    Step 5: Create a way to set the person bean’s name attribute
    The action executes when the user hits the enter key. This works only on the desktop profile. Notice below where the action function will set the personBean’s name attribute to the text entered into TextBox. This is a JavaFX common profile TextBox component.

    // create the view or form (in this case just a textbox)
    // This will manually set person.name to personForm2.text
    var personForm2:TextBox = TextBox{
                    text: ""
                    columns: 12
                    selectOnFocus: true
                    action: function(){
                        personBean.name = personForm2.text
                    }
    }

    Conclusion

    Although I have comments and debug statements you will notice how simple and very little code to achieve the presentation model pattern. In the near future I would bet that there will be JavaFX application frameworks which will make form type application development with ease. Any comments are welcome. Enjoy!