30 Lines of JavaFX Coding Challenge Theme – Time

1 10 2009

Space Time

My entry is called ‘Space Time‘. A 3D cube clock.

Wow, it is amazing at what you can you do in 30 lines of JavaFX code or 3000 characters.   JFXStudio is running a contest and the theme has to do with “TIME”. Although I posted my entry very last minute, there will be other chances for you to enter. Please visit http://jfxstudio.wordpress.com/2009/08/31/jfxstudio-challenge-small-is-the-new-big/

Space Time

Space Time

My entry including the import statements are just at 30 lines with each line containing less than or equal to 100 characters.  Click on the image to launch the demo.

Instructions:

  • Observe the cube rotating as each tick a second.
  • Observe the Space Time Title’s Distant lighting effect as seconds go by
  • Use mouse drag to rotate 3D cube
  • import javafx.animation.*;import javafx.scene.*;import javafx.scene.paint.Color;import javafx.scene
    .effect.*;import javafx.scene.text.*;import javafx.scene.shape.*;import javafx.scene.input.
    MouseEvent;import javafx.util.Math;class P{var x:Number;var y:Number;var z:Number;var sX:Number;var
    sY:Number;}class E{var a:Integer;var b:Integer;}var w:Number=800;var h:Number=600;var a:Number=30;
    var e:Number=30;var vs:P[]=[];function av(x:Integer,y:Integer,z:Integer){insert P{x:x,y:y,z:z}into
    vs;}av(-1,-1,-1);av(-1,-1,1);av(-1,1,-1);av(-1,1,1);av(1,-1,-1);av(1,-1,1);av(1,1,-1);av(1,1,1);var
    es:E[]=[];function aE(a:Integer,b:Integer){insert E{a:a,b:b}into es;}aE(0,1);aE(0,2);aE(0,4);aE(1,3
    );aE(1,5);aE(2,3);aE(2,6);aE(3,7);aE(4,5);aE(4,6);aE(5,7);aE(6,7);var ps:Circle[]=[];var ls:Line[]=
    [];function mps(c:Boolean):Void{var th:Number=bind 0.017453*a;var ph=0.017453*e;var cT=Math.cos(th)
    ;var sT=Math.sin(th);var cP=Math.cos(ph);var sP=Math.sin(ph);var cTcP=cT*cP;var cTsP=cT*sP;var sTcP
    =sT*cP;var sTsP=sT*sP;var sf=bind w/4;for(i in[0..sizeof vs-1]){var x0=vs[i].x;var y0=vs[i].y;var
    z0=vs[i].z;var x1=cT*x0+sT*z0;var y1=-sTsP*x0+cP*y0+cTsP*z0;var z1=cTcP*z0-sTcP*x0-sP*y0;x1=x1*3/(
    z1+4.5);y1=y1*3/(z1+4.5);vs[i].sX=x1;vs[i].sY=y1;if(c)insert Circle{centerX:bind w/2+sf*vs[i].sX+.5
    ,centerY: bind h/2-sf*vs[i].sY+.5,radius:2 fill:Color.BLUE}into ps;}if(c)for(e in es){insert Line{
    startX:bind ps[e.a].centerX startY:bind ps[e.a].centerY endX:bind ps[e.b].centerX endY:bind ps[e.b]
    .centerY strokeWidth:2,stroke:Color.BLUE}into ls;}}mps(true);var mx:Number;var my:Number;var g:
    Rectangle=Rectangle{x:0,y:0 width:bind w,height:bind h fill:Color.BLACK onMousePressed:function(me:
    MouseEvent):Void{mx=me.x;my=me.y;}onMouseDragged:function(me:MouseEvent):Void{var new_mx=me.x;a-=
    new_mx-mx;var new_my=me.y;e+=new_my-my;mx=new_mx;my=new_my;mps(false);}}var ct:String=new java.util
    .Date().toString();var tz:Integer=-125;var t=Group{content:[Text{effect:Lighting{light:javafx.scene
    .effect.light.DistantLight{azimuth:bind tz elevation:40}surfaceScale:5} x:10 y:50 content:"Space "
    "Time" fill:Color.RED font:Font{name:"Arial Bold" letterSpacing:0.20 size:50}},Text{x:10 y:80
    content:bind ct fill:Color.BLUE font:Font{name:"Arial Bold" letterSpacing:0.20 size:20}}]}var bc=
    Group{content:[Rectangle{x:10,y:bind h-85,arcHeight:5,arcWidth:5,width:bind w-30,height:30,fill:
    Color.RED,opacity:.5},Text{effect:DropShadow{offsetX:10,offsetY:10,color:Color.BLACK,radius:10}
    opacity:.5 x:15,y:bind h-65,content:"by Carl Dea - carlfx.wordpress.com"fill:Color.WHITE font:Font{
    name:"Arial Bold"letterSpacing:.20 size:20}}]}var scene:Scene=Scene{content:bind[g,ps,ls,t,bc]};var
    anim=Timeline{keyFrames:[KeyFrame{time:1s action:function():Void{a-=1;mps(false);ct=new java.util.
    Date().toString();if(tz>125){tz=-125;}tz+=2;}}]repeatCount:Timeline.INDEFINITE};anim.play();javafx.
    stage.Stage{width:bind w with inverse height:bind h with inverse scene:scene}

    Enjoy!
    Please vote for me…
    Let me know what you think. :)





    JavaFX Forms Framework Part 5

    4 09 2009

    Introduction

    Tilghman Island

    Tilghman Island

    This is the final part in a five part series of entries creating a proof of concept for a JavaFX forms framework.  Here, I will conclude with some thoughts relating to using JavaFX to build a forms framework. If you are here for the first time I recommend going to the beginning: Part 1 “What is a Forms Framework?.  By now we should know why it is very important to understand the MVC architectural pattern and how it applies when building applications (especially form type applications). The forms framework helps provide manageable code and clear boundaries for both the designer role and developer role. This allows a designer to focus on the usability (look and feel) of the application meanwhile allowing the developer to focus on the service components and business logic. Next, I want to talk about the popular and ambiguous acronym ‘RIA’ (better known as rich internet application).  You are probably wondering what does RIA have anything to do with a MVC forms framework?  Well, let me try to explain. To some people ‘RIA’ is a buzzword and to some people its actually a tangible software development platform. I have a hunch that some people are not convinced they should jump on the bandwagon or not.  But whatever you choose to agree with, I believe as we slowly become convinced what RIA is and how it fits into our domain an MVC forms framework should always be considered when building larger scale forms based applications. I want to begin by discussing RIA from a Swing/Web/Enterprise developer point of view (considering that’s my background).

    Swing/Web/Enterprise Developer

    Like most of us who had previously come from an enterprise background noticed the Web 2.0 looking applications getting lots of attention.  Whenever I hear the word RIA, I really think that it should be called  “Rich Applications” and drop the ‘I‘ because all clients should look and feel great regardless if they were connected to the Internet or not. So, usability is key to making client side applications connect with users. This year I was fortunate to go to JavaOne 2009 and experience all things rich client (some enterprise) and one of my last sessions was about Craftsmanship in Software from Ben Galbraith. He mentions “the most important aspect of software creation: crafting an amazing user experience.” This makes me realize that as applications become richer, consumers will demand richer content (a vicious cycle).  But,  I still believe enterprise-y looking applications (not so flashy)  using Swing will still have its place in the world of rich client. When developing rich clients I’ve found Swing GUI development to be quite pleasant to work with, however at times certain things  seem pretty hard to do such as animation, binding, and validation.

    Martin Jet Pack

    Martin Jet Pack


    JavaFX

    If you are like me who enjoys software development will learn over time some good proverbs and principles that surface. One saying I’ve heard was “Letting Go of Your Bananas”, which can be applied to your life and not just software. In terms of software I feel its OK to let go of some things and embrace other things. So, it’s healthy to be early adopters, but always keeping in the back of your mind past concepts that are tried and true.  An example would be “Swing/Web Frameworks” where everyone created their own or used the vast number of open-source libraries out there.

    Rocket man - melbourne show (Fir0002/Flagstaffotos)

    Rocket man - melbourne show (Fir0002/Flagstaffotos)

    Conclusion

    As the JavaFX community matures I believe forms based frameworks, GUI tools and application frameworks should start appearing, making many developers’ jobs much easier. I think there will be a day where Java developers around the world will not think ‘Swing is Hard‘, but say ‘JavaFX is extremely Easy‘. I encourage you as the reader to explore and learn as much as you can about JavaFX because it’s not every day that you can start from the beginning to learn a soon-to-be-popular language. Enjoy!





    JavaFX Forms Framework Part 4

    29 08 2009

    Introduction

    (Updated)** Added JavaFX Script code to represent a display panel mapping instead of the XML format example in the ‘User of the API (Application Developer)’ section.

    (Thanks! Andres Almiray)


    This is the forth installment of a series of blog entries relating to a proof of concept for a JavaFX Forms Framework.

    Chairman and Co-Founder, Sun Microsystems. (person on the left)

    Chairman and Co-Founder, Sun Microsystems. (person on the left)

    If you missed the beginning of the series you may go to Part 1, Part 2 and Part 3. Before we discuss this section I want to recap for those who have been following along. Part 1 explains “What is a Form based framework?” and a demo application. Part 2 describes the requirements and design. Part 3 are the implementation details. As we near the end of the series in Part 4 we will discuss enhancements that could be added to improve the FXForms framework. Below is a summary of the features from two user perspectives, first being the ‘User of the API’ and secondly the ‘User of the application’. I will only explain in detail the ‘User of the API‘ perspective.

    Features

    User of the API (Application Developer)

    • Mapping files (forms to beans)
    • GUI Component factory – make use of other controls

    User of the application (User experience)

    • Icon error, warn, info indicators overlay
    1. Override images to load and position when validation occurs.
    2. Error / Exceptions / Global errors
    3. Tooltips
    • Transitions to forms (fading, sliding, etc)
    • Focus Policy
    • User feedback (block gui visually) busy, indeterminate state.
    • Skinning and Themes for Forms
    • Context sensitive help
    • Sound effects

    User of the API (Application Developer)

    The goal here is to make life easier for the Application developer developing JavaFX Forms.

    The features are as follows:

    • Mapping Files – This provides custom bindings to field elements and bean properties. Also provides mappings for actions and controls.
    • GUI Component factories – Display panel managers (form manager) to assemble and wrap components to provide presentation model pattern behavior.

    1) Mapping files (forms to beans) – Display panels (forms) will be mapped to a particular Java Bean class. Each field will be mapped based on the bean property ‘name’ and the GUI widget’s ‘id’ attribute. When defining a display panel in XML it is a good idea to create a DTD or Schema, but for brevity I will not create them, and I will describe each XML element in detail such as default values, enumerated types, etc. an object representing fields and their corresponding bindings and actions will be called a ‘Display Panel Metadata’ object.

    When mapping fields and controls here are situations you will encounter:

    • Nested properties – Nested objects ie: Person references an object Address with a property called city. (use  ‘address.city‘)
    • Mapping bean properties with different GUI component ids. ie: Person bean property is ‘fName‘ and the TextBox’s id is ‘firstName
    • Custom bindings (list models single select, multi-select and contains all). ie: ListBox containing all objects in a collection owned by Person.
    • Action mappings to events and controls. ie: Buttons are mapped to functions in modules (script level functions).

    Below is an example of an XML mapping file might look like:

    Please skip this mapping file and go to JavaFX script code right after it. XML mapping file is replaced by JavaFX script code.


    <displayPanels>
      <!--
      *************************************************************************
      **** NO LONGER IN USE, DEPRECATED,                                  *****
      **** Please DISREGARD.
      **** REPLACED WITH JavaFX DisplayPanelMetadata class                *****
      *************************************************************************
      --------------------------------
      - Full Name Form Display Panel -
      --------------------------------
      This describes all gui widgets and actions.
        * Text control bound to a different named bean property 'fName'
        * Radio buttons bound to bean property 'likesFood'
        * Spinner control bound to bean property 'dateOfBirth'
        * Spinner control bound to bean property 'shoeSize'
        * List or combo control bound to nested bean property 'address.state'
        * List box control bound to nested bean property 'contacts' (collection)
        * List box control bound to nested bean property 'relatives' (collection)
        * Button control bound to action handler 
      -->
      <displayPanel id="FullNameForm" 
        className="com.company.forms.FullNameForm" 
        beanClass="com.company.domain.model.PersonBean" 
        presentationModel="com.company.domain.model.personpresentationmodel.EditPersonPM" 
        reuseForm=”true”>
    
        <!--First Name Field -->
        <textControl id="firstName" name="fName"/>
    
        <!-- Likes Food (yes or no)-->
        <radioButton id=”no”
          name=”likesFood”
          selectedValue=”true”
          bindingType=”BOOLEAN_TYPE”/>
        <radioButton id=”yes”
          name=”likesFood”
          selectedValue=”false”
          bindingType=”BOOLEAN_TYPE”/>
    
        <!--Date of Birth Spinner control-->
        <spinner id=”dob”
          name=”dateOfBirth”
          defaultValue=”null”
          bindingType=”DATE_TYPE”/>
    
        <!--Shoe Size Spinner control-->
        <spinner id=”shoeSize”
          name=”shoeSize”
          defaultValue=”5”
          minimumValue=”2”
          maxValue=”18”
          stepValue=”1”
          bindingType=”NUMBER” />
    
        <!--US State Drop Down List control-->
        <listModel id="address.state" 
          uniqueElementProperty="code" 
          displayName="${name}" />
    
        <!--Contacts List Box control-->
        <listModel id="contacts" 
          uniqueElementProperty="id" 
          displayName="${firstName} ${lastName} – (${id})" 
          bindingType="MULTIPLE_SELECT" />
    
        <!--Relatives List Box control-->
        <listModel id="relatives"
          name="relatives" 
          uniqueElementProperty="id"
          displayName="${firstName} ${lastName} – (${id})" 
          bindingType="CONTAINS_ALL" />
    
        <!--Save Button control-->
        <action id=”saveAction” 
          name="saveAction" 
          module="com.company.domain.forms.personactions" 
          function="updatePerson" 
          listener="java.awt.event.ActionListener"/>
    
      </displayPanel>
    </displayPanels>
    

    Line 15-19 Defines a form or display panel.

    Line 22 Maps a text field when a bean property and GUI control are named differently. Framework should assume if the name and id are the same and at text control developer doesn’t need to map. This keeps the XML mapping file smaller.

    Line 24-32 Custom binding for radio controls. Other scenarios exist, but for a simple boolean value selection the ‘BOOLEAN_TYPE’

    Line 34-38 Custom binding for a JSpinner. The bean property is a java.util.Date.

    Line 41-47 Custom binding for a JSpinner. The bean property is an int.

    Line 49-52 Custom binding for a dropdown list. The bean property is a java.lang.String. Notice the nested properties. When a form displays a nested property on the same form.

    Line 54-58 Custom binding for a List box. This is not bound to a bean property but a populated list allowing the user to select multiple items.

    Line 60-65 Custom binding for a List box. This is bound to a bean property referencing a collection of objects. Notice the “CONTAINS_ALL” which means all items in the list box are synchronized inside the collection.

    Line 67-72 Action mapping for a button on the form. They are named so actions can be reused such as menu or toolbar.

    Disregard the XML mapping file above. The same representation is below in JavaFX script code defining a display panel.

    **IMPORTANT NOTE: Since JavaFX is a declarative language which can achieve the same thing as a mapping file, I have re done the XML in JavaFX below:

    var displayPanelMetadata:DisplayPanelMetadata =  DisplayPanelMetadata {
      id: "FullNameForm"
      className: "com.company.forms.FullNameForm"
      reuseForm: true
    
      // Custom bindings to field elements
      customBindings: [
        // First Name Field 
        TextControlMetadata{
            id: "firstName"
            name: "fName"
        },
    
        // Likes Food (yes or no)
        RadioButtonMetadata {
            id: "no"
            name: "likesFood"
            selectedValue: "false"
            bindingType:"BOOLEAN_TYPE"
        },
    
        RadioButtonMetadata {
            id: "yes"
            name: "likesFood"
            selectedValue: "true"
            bindingType:"BOOLEAN_TYPE"
        },
    
        // Date of Birth Spinner control
        SpinnerMetadata {
            id: "dob"
            name: "dateOfBirth"
            defaultValue:"null"
            bindingType: "DATE_TYPE"
        },
    
        // shoe size
        SpinnerMetadata {
            id: "shoeSize"
            name: "shoeSize"
            defaultValue: "5"
            minimumValue: "2"
            maxValue: "18"
            stepValue: "1"
            bindingType: "NUMBER_TYPE"
        },
    
        // state selection
        ListModelMetadata {
            id: "address.state"
            uniqueElementProperty:"code"
            displayName:"${name}"
        },
    
        // contacts List Box control (not bound to bean)
        ListModelMetadata {
            id: "contacts"
            uniqueElementProperty:"id"
            displayName: "${firstName} ${lastName} – (${id})"
            bindingType: "MULTIPLE_SELECT"
        },
    
        // relatives(family) List Box control
        ListModelMetadata {
            id: "relatives"
            name: "relatives"
            uniqueElementProperty:"id"
            displayName: "${firstName} ${lastName} – (${id})"
            bindingType: "CONTAINS_ALL"
        }
      ] // custom bindings sequence
    
      // Save Button control
      actions:[
          ActionMetaData {
          name: "saveAction"
          module: "com.company.domain.forms.personactions"
          functionReference: "updatePerson"
        }
    
        ] // actions
    
    } //displayPanel

    Line 0-3 Defines a form or display panel.

    Line 8-11 Maps a text field when a bean property and GUI control are named differently. Framework should assume if the name and id are the same and at text control developer doesn’t need to map. This keeps the metadata mapping info smaller.

    Line 14-19 Custom binding for radio controls. Other scenarios exist, but for a simple boolean value selection the ‘BOOLEAN_TYPE’

    Line 29-34 Custom binding for a JSpinner. The bean property is a java.util.Date.

    Line 37-45 Custom binding for a JSpinner. The bean property is an int.

    Line 48-52 Custom binding for a dropdown list. The bean property is a java.lang.String. Notice the nested properties. When a form displays a nested property on the same form.

    Line 55-60 Custom binding for a List box. This is not bound to a bean property but a populated list allowing the user to select multiple items.

    Line 63-69 Custom binding for a List box. This is bound to a bean property referencing a collection of objects. Notice the “CONTAINS_ALL” which means all items in the list box are synchronized inside the collection.

    Line 74-77 Action mapping for a button on the form. They are named so actions can be reused such as menu or toolbar.

    2) GUI Component factory – make use of other controls

    Forms can be retrieved and populated using convenient factory functions. When assembling a form and mapping properties the underlying implementation may have a configuration file to have modular ways to specify what controls will be used for binding controls.

    var personForm = FormManager.retrieveForm(personBean, 'FullNameForm');

    Conclusion

    While some features of the ‘User of the Application‘ perspective may seem debatable, I believe a forms framework should at least have all the features described in the ‘User of the APIs‘ perspective. As a framework implementer one should design a plug-able architecture for custom components. Components should be wrapped and registered when assembling a form. I’m sure there are many features I have not mentioned.  As JavaFX matures I believe GUI builders providing WYSIWYG development will eventually allow third party GUI controls to be added to their control palette. Next, I will discuss Part 5 Concluding thoughts.

    Like always, any comments are welcome!





    JavaFX Forms Framework Part 3

    20 08 2009

    Introduction

    Matthew 7:13-14

    Matthew 7:13-14

    This is the third installment of a series of blog entries relating to a proof of concept for a JavaFX Forms Framework. If you missed the beginning of the series you may go to Part 1 and Part 2. We will take a look at code snippets relating to how the FXForms Framework was implemented. If you want to jump right into the code you may download it here or browse the source code here from the JFXtras Samples area. To those who are following the series will notice similarities to JGoodies Bindings and Validation libraries, it is because of those libraries and presentations which basically inspired me to create this MVC forms framework in JavaFX.

    Disclaimer: Most of the code snippets will deal with the user of the API’s perspective as opposed to the implementer of the API’s perspective in order to keep the blog entry short. I will try my best to touch on areas regarding the framework’s underlying implementation. I advise people to check the code project out, review it and run it.

    A thing I’d like to bring to your attention is that I decided to refactor the code a little and add a new feature to the FXForms Framework. I refactored the form to reference an instance of a presentation model instead of inheriting from it. As I mentioned in Part 2 the form will be independent of the presentation model. This provides different validation contexts while reusing the same form. An example of this situation is when a user uses a form to ‘Add’ information versus an ‘Edit’ of the form information. The new feature added is the ability to validate a field as the user is typing into the text box and positions an icon to indicate an error, warning or information to the user. Another feature might be to add tool tips when the mouse hovers over the icon similar to JGoodies’ IconFeedbackPanel behavior in Java Swing. Before going further into the implementation details you may want to launch the demo to get a feel for the behavior of the entry form with validation and icon indicators.

    Demo

    Demo

    Instructions:

    • Enter numbers or symbols into the first, last and middle name field.
    • Click on the check box to swap the JavaBean for the form.
    • Observe the underlying bean values changing.

    Next are the steps on how to develop the demo using the FXForms Framework.

    Developer Steps

    1. Create a JavaBean representing a domain object.
    2. Create a Presentation Model with validation for a Form.
    3. Create a Form
    4. Associate a Presentation Model to Form
    5. Use the Form in an application

    Detailed Steps

    Step 1. Create a JavaBean representing a domain object.

    // Java
    public class PersonBean extends DomainModel{
        public static final String FIRST_NAME_PROPERTY = "firstName";
        public static final String MIDDLE_NAME_PROPERTY = "middleName";
    ... // more strings naming properties
        private String firstName;
        private String middleName;
    ... // more attributes
    
        /**
         * Returns first name of the person.
         * @return
         */
        public String getFirstName() {
            return firstName;
        }
    
        /**
         * Sets the first name of the person.
         * @param firstName
         */
        public void setFirstName(String firstName) {
            String old = this.firstName;
            this.firstName = firstName;
            firePropertyChange(FIRST_NAME_PROPERTY, old, firstName);
        }
    ... // the rest of the methods.
    }

    PersonBean.java - A domain object containing property change support.

    DomainModel.java – Abstract base class containing property change support.

    Step 2. Create a Presentation Model with validation for a Form

    As I mentioned earlier about reusing the same form with different presentation models. Below you will see an ‘Add Form’ with validation on the Last Name field. The error icon indicates that the last name may not contain symbols and numbers, but allowing letters, apostrophe or hyphen in the name. You will notice the red error icon beside the ‘last name’ text field.

    Add Form validation on last name field.

    Add Form validation on last name field.

        // JavaFX
        var personForm:NameForm = NameForm{
            presentationModel:domain.model.personpresentationmodel.AddPersonPM{}
        };
        personForm.presentationModel.jBean = new PersonBean();

    Next, you will see an ‘Edit Form’ with no validation on the ‘Last Name’ field. But, there is validation on the ‘First Name’ field. The warning icon indicates that the first name can contain symbols and numbers, letters, apostrophe or hyphen, but isn’t recommended. You will notice the yellow warning icon beside the ‘first name‘ field.

    Edit Form no validation for Last Name field

    Edit Form no validation for Last Name field

        // JavaFX
        personForm.presentationModel = domain.model.personpresentationmodel.EditPersonPM{}
        personForm.presentationModel.jBean = personBean2;

    *Note: The examples above are two hypothetical use cases, I mocked up those forms to help illustrate different validation contexts. The demo app uses an edit presentation model that does validate on the ‘last name‘ field.

    Edit Person Presentation Model w/Validation

    // JavaFX
    public class EditPersonPM extends fxforms.model.model.PresentationModel {
    
       /** Validate the first name field */
       var validateFirstName =  Validator{
           id:PersonBean.FIRST_NAME_PROPERTY
           public override function validate(value:Object){
               return validateName(value, PersonBean.FIRST_NAME_PROPERTY, "Warning");
           }
       };
    ... // more validators
       postinit {
           addValidator(validateLastName);
           addValidator(validateFirstName);
           addValidator(validateMiddleName);
       }
    }
    // Script level function
    /**
     * Using regular expression allow letters, apostrophe, hyphen
     */
    function validateName(value:Object, propName:String, messageType:String){ // use friendly names, short names, etc.
        var results = ValidationResult{};
        var strValue:String = value as String;
        var found:Boolean = Pattern.matches("^[a-zA-Z,'.\\-\\s]*$", strValue);
        if (not found) {
            var message:FieldMessage = FieldMessage{
                id:propName
                messageType:messageType
                errorId:"123"
                errorMessage:"No symbols in names except - or ' (apostrophe)"
            }
            results.addMessage(message);
        }
        return results;
    }

    Line 01: Class EditPersonPM extends fxforms.model.model.PresentationModel
    Line 04: var validateFirstName is an instance of a Validator
    Line 12: Adds all Validators to the presentation model
    Line 21: Script level function to be used in each validator
    Line 24: Regular expression to allow letters, apostrophe and hyphen characters only.
    Line 26: Creation of the message when Validator validates.

    personpresentationmodel.fx – The edit presentation model for a person name form.

    model.fx - Contains presentation model and value model implementation.

    validation.fx – Contains the validator, message, result classes.

    Step 3. Create a Form

    Edit Person Form (Screen mockup)

    0 full name panel
    +-1------------------------+ // VBox with 3 things
    ! +-2--------------------+ ! // HBox with 2 things
    ! ! [ 3 ] [ 4           ]! ! // Label(section) and Label(title)
    ! +----------------------+ !
    ! +-5--------------------+ ! // HBox with 2 things
    ! ! [ 6 ] [ 7  ]         ! ! // Label(spacer} and Text(instructions)
    ! !                      ! ! // wrapping text abilities
    ! +----------------------+ !
    ! +-8--------------------+ ! // HBox with 2 things
    ! ! +-9---+ +-10-------+ ! ! // VBox_9(labels) Vbox_10(textbox)
    ! ! ![11] ! ! [15]     ! ! ! // Label(lastname) TextBox()
    ! ! ![12] ! ! [16]     ! ! ! // Label(firstName) TextBox()
    ! ! ![13] ! ! [17]     ! ! ! // Label(mi)  TextBox()
    ! ! ![14] ! ! [18]     ! ! ! // Label(suffix)  TextBox()
    ! ! +-----+ +----------+ ! !
    ! +----------------------+ !
    +--------------------------+

    NameForm inherits from Form
    Form inherits from CustomNode

    // JavaFX
    public class NameForm extends fxforms.ui.form.Form {
       public override function create():Node{
            // 0 main panel
            var mainPanel:Panel = Panel{
                content:[]
            }
            ... // more layouts and widgets
    
            var firstLabel:Label = Label {
                text: "First Name"
                hpos:HPos.RIGHT
                font : Font {
                    size: 18
                }
                layoutInfo: LayoutInfo { minWidth: 100 width: 150 maxWidth: 200 }
            };
            ... // more code
            var lastNameTextBox:TextBox = fxforms.ui.controls.MyTextBox {
                id:"lastName"
                columns:20
            };
            var miNameTextBox:TextBox = fxforms.ui.controls.MyTextBox {
                id:"middleName"
                columns:20
            };
            ... // more fields
    
            // *** NOTE: This is for easy lookup. And relating to Scene.lookup(id) bug in 1.2.
            guiFields = [lastNameTextBox, firstNameTextBox, miNameTextBox, suffixNameTextBox];
            presentationModel.addGuiFields(guiFields);
            return mainPanel;
        } // create()
    } // NameForm

    NameForm.fx - This represents a Form containing a person’s name information.

    form.fx – This is the base class which contains the presentation model for forms binding behavior.

    controls.fx – This contains all registered GUI controls for observing value model value changes. Currently only one control exists the TextBox control.

    *Note: The ideal way to build forms is using the JFXtras MigLayout library. To learn more take a look at Dean Iverson’s blog entry called “MigLayout for JavaFX Reloaded“.

    Step 4. Associate a Presentation Model to Form

    // JavaFX
    var personForm:NameForm = NameForm{
        presentationModel:domain.model.personpresentationmodel.EditPersonPM{}
        translateX: bind slideFormX
    };
    var personBean2:domain.model.PersonBean = new domain.model.PersonBean();
    personBean2.setFirstName("Squidward");
    personBean2.setLastName("Tentacles");
    personBean2.setMiddleName("Nickelodeon");
    personBean2.setSuffixName("Sr.");
    
    // set presentation model with domain object
    personForm.presentationModel.jBean = personBean2;

    Line 02: Associate presentation model to form
    Line 05: Create an instance of a JavaBean
    Line 12: Bind bean to presentation model and form

    Once the presentation model and form are assembled binding an existing Java object is a snap. In part 4 on enhancing this process would be to create a factory to obtain meta information of the form to retrieve nested properties within a POJO/JavaBean off of the JavaFX main thread (desktop profile is the EDT). This effort will help alleviate from the dreaded Hibernate lazy init exception when using detached objects. So, making sure you don’t block the GUI thread is a big deal when it comes to user experience.

    Step 5. Use the Form in an application

        var switchPersonButton:CheckBox = CheckBox {
                text: bind personToSwitchText
                width: 100
                translateX: 5
                translateY: bind mainScene.height - switchPersonButton.height - 5
                allowTriState: false
                selected: false
                override var onMouseReleased = function(e:MouseEvent):Void {
                    if (selected){
                       personToSwitchText = "Sponge Bob";
                       personForm.presentationModel.jBean = personBean1;
                    } else {
                       personToSwitchText = "Squidward";
                       personForm.presentationModel.jBean = personBean2;
                    }
                }
            };
    
        var mainScene:Scene = Scene {
            fill: LinearGradient {
                        startX: 0
                        startY: 0
                        endX: 0
                        endY: 1
                        stops: [
                            Stop { offset: 0.1 color: Color.ORANGE },
                            Stop { offset: 1.0 color: Color.YELLOW },
                        ]
                    }
            content: [personForm, switchPersonButton, backButton, nextButton]
        };

    Main.fx - The main application file to launch the application

    Value Model

    The ‘Value Model‘ is probably the most important aspect of how the Forms binding works. The value model is a model that holds a single value that notifies registered listeners that a value has changed. Registered listeners will likely be GUI controls and JavaBean properties. Bidirectional binding occurs when a bean property value changes, which notifies the value model which updates the  GUI control value. This holds true when going in the other direction too, such as the user changes the value of the GUI control which notifies the value model which updates the JavaBean property value.

    model.fx – Contains presentation model and value model implementations.

    Conclusion

    I feel the implementation of the fxforms framework using JavaFX was extremely easy and is a lot less code compared to a Java equivalent of a Swing/SWT forms framework, also carrying additional overhead using 3rd party libraries for binding and validation. As JavaFX matures with more controls the forms framework would need to be flexible enough to add any controls to handle custom bindings such as list models.  Next we will look at Part 4 Enhancements . As always any feedback is welcome!

    References

    Validation presentation by Karsten Lentzsch – http://www.jgoodies.com/articles/validation.pdf

    JGoodies: http://www.jgoodies.com/

    JGoodies Support: http://www.jgoodies.com/products/purchase.html

    The Unknown JavaBean by Richard Bair – http://weblogs.java.net/blog/rbair/archive/2006/05/the_unknown_jav.html

    JavaFX – JMS Unexpected Null Pointer Exception http://blogs.sun.com/clarkeman/entry/javafx_jms_unexpected_null_pointer

    JFXtras Community Site – http://jfxtras.org/portal/home





    JavaFX Forms Framework Part 2

    3 08 2009

    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





    JavaFX Forms Framework Part 1

    29 07 2009
    Full Name Form with Validation

    Full Name Form with Validation

    Introduction

    Software developers creating form based applications will inevitably stumble across the single most important architectural design pattern “Model View Controller” or “MVC in short. This concept has paved the way for many frameworks which provide true separation of concerns. The main idea of these MVC frameworks are to separate content from presentation. In layman’s terms I call them “Forms Framework“. When building enterprise applications with a forms framework the ability to achieve rapid application development and developer productivity will increase greatly. I would like to create a series of blog entries (five parts) detailing a simple proof of concept of a mini forms framework. Below is a brief summary of the five part series:

    Part 1 - What is a Forms Framework? Also a quick demo of a simple form application.
    Part 2 - Requirements and design
    Part 3 - Implementation details
    Part 4 - Enhancements
    Part 5 - Concluding thoughts

    Other Form based technologies

    Although the form based technologies listed above use vastly different ways to build form based applications, they all are basically using the MVC based architectural pattern. My intent is reuse existing Java domain objects POJOs while using JavaFX as a front-end thus providing a return on investment on legacy system domain models. While mature Java technologies like JAXB, EJB and Hibernate still dominate the Java enterprise the idea is to reuse what we already have.  JavaFX was developed from the ground up with MVC in mind such as the “Designer-Developer Workflow“. So, with a forms framework a Java Bean would bind to a Presentation Model and a JavaFX Form. I will call the mini forms framework “FXForms” framework throughout the series.

    Demo

    A form containing JavaFX textbox components to capture a person’s full name.

    Instructions:

    • Check Box to toggle two people using the same form
    • Type and change information in fields, thus changing the underlying bean
    • Click on Next for a transition to next form.
    • Click on Back to return to form

    Click here to run demo

    Conclusion

    Many who have already read my entry regarding JavaFX Presentation Model Pattern Using Binding. Here, I have decided to kick it up a notch and actually develop a mini forms framework to make forms development easier than ever.  JavaFX is an excellent choice to create nice looking GUI forms that will easily bind to your domain model. Next Part 2, we will take a look at requirements for a forms framework.





    JFXtras Community Site

    20 07 2009

    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 to JavaScript and Back Part 2

    9 07 2009
    Tons of Bouncy Balls

    Tons of Bouncy Balls

    Introduction

    In the second installment of the series “JavaFX to JavaScript and Back” we will look at code! If you remember what we discussed in my previous post of Part 1 showing a demo of many bouncy balls. If you want to skip to the source code go to demo and click on download project.

    Newcomers

    If you are new and just getting started with JavaFX I strongly suggest JavaFX.com or Java.sun.com. If you are like me, one who knows enough to be dangerous please skip to Getting Started. Newcomers should take a look at books in the References section at the end of this article. Another awesome resource is the “Free” 15-Week JavaFX Programming (with Passion!) Online Course w/ Sang Shin & James Weaver.

    Assumptions

    • NetBeans 6.5.1 is installed with JavaFX 1.2 pluggin.
    • Java SDK 1.6 update 14
    • Know basic JavaScript
    • Know basic HTML

    Getting started

    To give you a quick recap of the scenarios:

    1. Create Bouncy Balls (JavaScript to JavaFX)
    2. Remove Bouncy Balls (JavaFX to JavaScript)

    Create a JavaFX Applet

    Step 1: Create a Ball (Custom Node)
    First create a class called Ball that extends a CustomNode. The key is overriding the create() method of the CustomNode class. We first create a Circle with a RadialGradient fill. Next we create a Group containing the circle in its content attribute. Then add the onMousePressed function to the group to detect a mouse pressed event which will remove this ball’s instance from the Scene (Game Area) and decrements the numBalls variable which updates the Web Page’s form element Number of Balls. Finally we return the group (ball variable).

    class Ball extends CustomNode {
        public var velocity:Velocity;
        public var centerX:Integer=100;
        public var centerY:Integer=100;
        public var radius:Integer;
        public var fill:Color;
        protected override function create(): Node {
            var circle:Circle = Circle {
                    centerX: centerX, centerY: centerY
                    radius: radius
                    fill: RadialGradient {
                            centerX: centerX - radius / 3
                            centerY: centerY - radius / 3
    
                            radius: radius
                            proportional: false
                            stops: [
                                Stop {
                                    offset: 0.0
                                    color: getRndColor()
                                },
                                Stop {
                                    offset: 1.0
                                    color: Color.BLACK
                                }
                            ] // stops
                    } // RadialGradient
            } // circle
            var ball = Group{
                content:[circle];
                // remove ball
                onMousePressed: function( e: MouseEvent ):Void {
                    delete this from gameArea;
                    numBalls--;
                }
            } // Group
    
            return ball;
        } // create()
    } // Ball

    Step 2: Create initial ball to be put in Scene

    You should notice I’ve created a few script level functions which conveniently return random values to create a Ball node. I won’t list those function for brevity. The random generated attributes are: velocity, centerX, centerY, radius, circle.fill = (RadialGradient 1st stop Color [Step 1 - Line 19])

    // create an initial ball to float around.
    var initialBallRadius = getRndRadius();
    var rndCenter:Point = getRndCenter(500, 400, initialBallRadius);
    var firstBall = Ball{
        velocity:getRndVelocity()
        centerX: rndCenter.x
        centerY: rndCenter.y
        radius: initialBallRadius
    };

    Step 3: Create the Scene to display Balls
    The variable gameArea is a sequence of Nodes. You will notice the ball instance from Step 2 is the first node in the sequence. The scene’s content attribute is bound to the gameArea variable. During run time as nodes are added and removed from the game area the scene will dynamically update the visible nodes.

    var gameArea:Node[] = [firstBall, toggleAnimationButton, mainRectRegion];
    var scene:Scene = Scene {
            content: bind gameArea
            fill:Color.TRANSPARENT
    };

    Step 4: Create the Stage
    This is the top level container which holds the scene.

    Stage {
        title: "Application title"
        width: 500
        height: 400
        opacity: bind mainScreenOpacity;
        scene: scene
    }

    Step 5: Create a game or animation loop using the Timeline class
    Here we create a Timeline instance that will run indefinitely (Timeline.INDEFINITE) with a single key frame (KeyFrame) which periodically updates each bouncy ball’s attributes which eventually renders each ball node with a new x and y position based on the velocity. Also the Timeline (gameLoop) is started immediately using the play() function.

    var gameLoop:Timeline = Timeline {
        repeatCount: Timeline.INDEFINITE
        keyFrames : [
            KeyFrame {
                time: 1s / 50
                canSkip : true
                action: function() {
                    for (node:Node in gameArea) {
                        if (not (node instanceof Ball)){
                            continue; // don't update non balls
                        }
                        var ball = node as Ball;
                        var xMin = ball.boundsInParent.minX;
                        var yMin = ball.boundsInParent.minY;
                        var xMax = ball.boundsInParent.maxX;
                        var yMax = ball.boundsInParent.maxY;
    
                        // Collision - boundaries
                        if (xMin  scene.width){
                           ball.velocity.xVelocity = ball.velocity.xVelocity * -1;
                        }
                        if (yMin  scene.height){
                           ball.velocity.yVelocity = ball.velocity.yVelocity * -1;
                        }
    
                        ball.translateX = ball.translateX + ball.velocity.xVelocity;
                        ball.translateY = ball.translateY + ball.velocity.yVelocity;
                    }
                } // action
            } //
        ]
    };
    gameLoop.play();

    Step 6: Create the AppletStageExtension
    This is the reference to the JavaFX applet which would assist with browser functionality such as the evaluation of JavaScript code.

    var applet: AppletStageExtension;

    Step 7: Create the numBalls variable keeping track of adds and removes.
    The numBalls variable has a trigger (on replace) that updates the HTML page’s input text field “numBalls“. You should notice the id attribute of the tag is name “numBalls“. An id is a way to uniquely locate the form element in the HTML DOM (in this case a reference to the input field. When numBalls variable changes the trigger will evaluate the JavaScript code “document.getElementById(‘numBalls’).value = {numBalls}”. What this does is populate the form element field’s ‘id’ called “numBalls” whenever the JavaFX variable numBalls is updated.

    var numBalls:Integer = 1 on replace {
        applet.eval("document.getElementById('numBalls').value = {numBalls}");
    };

    Step 8: Create a JavaFX function to add lots of balls

    The HTML Web page will have a JavaScript function that would call the JavaFX function below when the user presses the Add Ball(s) button.  javafxtojavascriptandback8You will notice the FX.deferAction() call, which ensures updates to JavaFX classes are happening on the JavaFX main processing thread. This function will instantiate num balls inserts into the game area (Scene content) and increments the numBalls (trigger will update Web page’s form element).

    // This function is called from the JavaScript button and numBallsToAdd field
    function addBalls(num:Integer) : Void {
        FX.deferAction(function() : Void {
            for( i in [1..num]){
                var curBallRadius = getRndRadius();
                var rndCenter:Point = getRndCenter(500, 400, curBallRadius);
                var b = Ball{
                    velocity:getRndVelocity()
                    centerX: rndCenter.x
                    centerY: rndCenter.y
                    radius: curBallRadius
                    fill: getRndColor()
                };
                insert b into gameArea;
                numBalls++;
            }
        });
    }

    Create a HTML Web page containing the JavaFX applet

    Step 9: Create HTML Web page to display JavaFX applet

    Run in Browser

    Run in Browser

    After creating the project in NetBeans select project / properties / Run (categories) / Application Execution Model – Run in Browser.

    Step 10: Build Project

    Building the project which will create files in the {PROJECT_HOME}/dist directory.

    Step 11: Copy originally NetBeans created HTML file of the dist directory to another name

    Use the copied and renamed HTML file and not the original because when the build process occurs it will overwrite the original HTML generated file.

    Step 12: Modify HTML code to contain JavaScript to call JavaFX applet.

        javafx(
            {
                  archive: "JavaFXtoJavaScript.jar",
                  draggable: true,
                  width: 500,
                  height: 400,
                  code: "javafxtojavascript.Main",
                  name: "JavaFXtoJavaScript",
    			  id: "ballApp"
            },
    		{ isApplet: "true" }
        );
    
    function addBalls() {
    	document.ballApp.script.addBalls(document.getElementById('numBallsToAdd').value);
    }

    Step 13: Modify HTML to contain Form Elements.

    <form>
    <table>
    <tr><th>Add balls to Scene :</th>
    <td><input id=”numBallsToAdd” name=”numBallsToAdd” value=”1″/></td>
    <td><input onClick=”addBalls();” type=”button” name=”addButton” value=”Add Ball(s)”/></td>
    </tr>
    <tr>
    <th>Number of balls: </th>
    <td><input id=”numBalls” name=”numBalls” READONLY/></td>
    </tr>
    </table>
    <br/>
    </form>

    Running Applet in Browser through NetBeans

    Step 14: Run application or hit F6 key

    This will launch the JavaFX applet into the browser from the original HTML page created from the build. Go to the address and modify the URL (Just the file name) to use the modified copy which would run the JavaFX applet along with the form elements added from step 12 – 13.

    Conclusion

    Although the example only used simple attributes of the AppletStageExtension there are other properties and events to explore such as onAppletRestored, showDocument(), etc.  Hopefully we can get away from HTML and just have rich client applications, however I don’t think the browser is going away anytime soon. So we can happily go from JavaFX to JavaScript and Back!

    Enjoy. Let me know what you think.

    References:

    Pro JavaFX Platform by Jim Weaver, Weiqi Gao, Stephen Chin, and Dean Iverson
    JavaFX: Developing Rich Internet Applications by Jim Clarke, Jim Connors and Eric J. Bruno
    Essential JavaFX by Gail Anderson and Paul Anderson

    numBalls




    JavaFX to JavaScript and Back Part 1

    5 07 2009

    Introduction

    One of the most impressive features that I’ve seen relating to JavaFX, is the ability of an Applet to interact with the browser via JavaScript and HTML. The browser can also interact back with JavaFX code. There are plenty of examples out there but I’d like to add one more to the pile of cool examples. It may be cool using AJAX concepts with JavaScript & HTML, but using the concept with JavaFX is just amazing. The possibilities are endless. “JavaFX to JavaScript and Back Part 1” will demonstrate what the application will do and “JavaFX to JavaScript and Back Part 2” will be on steps on how-to do it.

    While I was a kid growing up, I would go to the bowling alley to get a 25 cent(US) bouncy ball from the vending machine. I’ve lost many a bouncy ball in the parking lot from bouncing them as hard as I could. In this example I will create a 500 by 400 pixel sized bouncy ball containment field in JavaFX. This is to prevent them from ever leaving me like they did when I was a kid. :-(

    Note: Thanks to Stephen Chin an author of the book Pro JavaFX Platform and WidgetFX for allowing me to host The Bouncy Ball Containment Field Click Here to run!

    (Tip: If in Firefox just middle mouse click link to launch in another tab)

    Initial Ball added to ball world

    Here is an example of an HTML page with an embedded JavaFX applet with HTML form elements below for data input to create bouncy balls. The demo allows a user to specify the number of balls to add to the scene called the “Add balls to Scene” field.  When the “Add Ball(s)” button is pressed the JavaScript code will pass the number of balls to the JavaFX public script level function called addBalls() which will create bouncy balls. When balls are added the JavaFX Script code will talk back to the HTML read-only field called “Number of balls” to show the current number of balls in the containment field (Scene). On the JavaFX side of things the location, velocity, size and color of the balls will be generated randomly and rendered on the scene.  You should notice the new JavaFX 1.2 Toggle Button component on the upper left. It is used to stop and  start the animation of the bouncing of the balls (Timeline pause & play to be exact). The first use case scenario is add balls which depicts the JavaScript to JavaFX data flow. The second use case scenario is display the current number of bouncy balls in the containment field which depicts the JavaFX to JavaScript data flow.

    Balls addBalls(lots of balls)

    This shows when the user specifies a whole bunch of balls to add.

    Button to use JavaScript function addBalls()
    Button to use JavaScript function addBalls()

    A ball can be removed from the scene by just clicking an individual ball.  The field “Number of balls” input field is really a read-only field that is updated from the JavaFX side whenever balls are added and removed from the bouncy ball containment field.

    More Bouncy Balls

    By adding many balls I wanted to see how well it would perform.

    Tons of Bouncy Balls

    Here I add balls, lots of balls! The bouncy ball containment field now holds 400 bouncy balls. Although I might not be doing things efficiently I noticed my CPU was performing adequately. The utilization was between 41% to 46% (older Dell hyper-threading Inspiron XPS laptop Pentium(R) 4 CPU 3.40 GHz) using Windows XP SP 3. It was a smooth animation with no flicker. The Ball class is a Custom Node which contains a Circle with an effect called Radial Gradient to give it a 3D sphere look.

    Dragging JavaFX Applet out of Web Page

    By using the Alt key along with mouse drag the JavaFX applet will appear to be pulled out of the browser’s Web page and out onto the desktop.

    JavaFX Applet living outside of browser

    By default, when you drag the applet out of the browser onto your desktop a small “close button” appears on the upper right corner of your application. When the user clicks the “close button” box the JavaFX applet will snap right back into the browser. Another thing to note is that when the JavaFX applet is running outside the browser and the user subsequently closes the browser the applet will remain running independent of the browser.   This introduces an interesting ability that adds a new dimension to usability on the desktop.  As the user becomes drawn into the application experience the need to be attached to the Web page will be obsolete. Another cool effect that I have added to the Application is transparency or opacity level when the mouse cursor is exiting or entering the scene area. When the user moves the mouse away from the application the screen will fade to a subtle transparency. When the user moves the mouse cursor into the application screen area the background becomes fully opaque (white in this case).

    Fully Opaque when mouse moves into application

    Fully Opaque when mouse moves into application

    This fading effect helps the user transition from one application to another.

    The last, item of the desktop experience to mention is the Java JNLP mechanism that asks the user if he or she wants to create a short-cut icon for the application to launch at a later time.

    Create short-cut dialog

    Create short-cut dialog

    To reproduce the dialog asking for a shortcut, you would drag the applet out of browser, then close tab or browser application and then a dialog will appear asking to create the short-cut.

    Conclusion

    Building the bouncy ball containment field was extremely fun. I learned a lot about boundsInParent which taught me that it is the rectangular region after all transformations to the node has been applied when adding balls to the Scene. As the future of the Web 2.0 apps grow users will demand richer interfaces and better content. I believe JavaFX has made great strides in desktop development and also increasing the usability factor of desktop applications by leaps and bounds. In Part 2 of “JavaFX to JavaScript and Back” I will detail a step-by-step tutorial on how to build the JavaFX applet you see here. Let me know what you think. Feedback is always welcome!





    JavaFX Strings vs Java Strings

    1 07 2009

    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.