Category Archives: Uncategorized

JavaFX in Action – Book Review

JavaFX in Action

I have been fortunate enough to read the e-book version of the book JavaFX in Action by Simon Morris through the Manning MEAP program. I subsequently did a detailed book review on the DZone‘s “IT Book Zone” area. Book Review: http://www.dzone.com/links/javafx_in_action.html . I highly recommend this book if you are a beginner or an experienced developer from any language background to create engaging Rich Internet Applications (RIA) ranging from game programming to business applications. It is an easy read and I’m very impressed with many bonus sections included in most chapters. This book is another great book to add to my JavaFX library.

JavaFX Library

JavaFX Library

Any feedback is welcome!

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!

JavaFX Init Block Setting Default Values

Introduction

To create default values in Java, an instance variable with a String data type we would often have null and empty string values by default. In JavaFX we can create default values the same, but also have the opportunity to determine if the instance variables have ever been initialized at all.  This is cool because you can ensure that values are valid before the values can be used. An example would be if you had a variable called distance which holds an Integer.  A distance could not be a negative so the init block implementer could ensure that anything less than zero will take on the value zero.  When using an init block, you can use JavaFX’s a built-in function called isInitialized(object:Object) located (javafx.lang.Builtins) to determine if the instance variable has been initialized.

public static boolean isInitialized(java.lang.Object varRef)

Example

In this example a class called Cat will have instance variables called name and age. The default values will be initialized inside of the init block after the instance variables get their values.

The Cat class’ requirements:

  • When the Cat is instantiated without values being set the values are considered null and not initialized. Name the cat ‘Felix’.
  • When the Cat is instantiated with values being set to null name the cat ‘Garfield’
  • When the Cat is instantiated with values being set to empty string name the cat ‘Tom’

Example

package initstuff;

/**
 * @author cdea
 */
class Cat {
    var name:String;
    init {

        // Default name setting when there are null or empty string values
        // Not initialized
        if (not isInitialized(name)){
            name = "Felix"
        } else {
            // Is initialized but with null or empty string as value
            if (name == null) {
                name = "Garfield"
            } else if (name.trim().equals("")){
                name = "Tom"
            }
        }
    } // init
}

var myCat = Cat{};
println("myCat's name is {myCat.name}");
var myCat2 = Cat{name:" "};
println("myCat2's name is {myCat2.name}");
var myCat3 = Cat{name:null};
println("myCat3's name is {myCat3.name}");

Output

myCat’s name is Felix
myCat2’s name is Tom
myCat3’s name is Garfield

Conclusion

This is very similar to constructors in Java, but in JavaFX you have a little more control of setting the values after values have been initialized. This will help prevent the user of the API to put invalid information when instantiating an object. Another example is that it ensures the values fall in a particular range.

JavaFX Init and Postinit Blocks Order

Introduction

I noticed in JavaFX there isn’t really the same kind of concept as a constructor in Java. I want to create an example that will show the order of the init block and postinit block execution when an object is instantiated. I created a super class (SuperClass) and a subclass (SubClass extends SuperClass) to see the order of init blocks and postinit blocks executed.

This is the order the init and post init block run execution:

  1. Init block executes right after the attribute values are set or initialized.
  2. Postinit block executes right after the object is finished initialized.

Example

package initstuff;

/**
 * This will simply display the order of init block order.
 * @author carldea
 */

var x:Integer = count();

function count():Integer {
   Main.x=Main.x+1;
};

class SuperClass{
   init {
      println("{x} SuperClass init block");
      count();
   }
   postinit{
      println("{x} SuperClass postinit block");
      count();
   }
}

class SubClass extends SuperClass{
   init {
      println("{x} SubClass init block");
      count();
   }
   postinit{
      println("{x} SubClass postinit block");
      count();
   }
}

var myJfxObject = SubClass{}

Output

1 SuperClass init block
2 SubClass init block
3 SuperClass postinit block
4 SubClass postinit block

JavaOne 2009 Woah, I know KungFu

Introduction

Woah, I know KungFu-Neo

I’m sure folks have seen the movie “The Matrix” where in the scene when Neo is downloading all the fight training programs to his tiny brain. Well, that was my experience at JavaOne.  Ok, maybe I’m being overly dramatic, but you must understand how long I’ve been wanting to go to this conference. So, coming back from JavaOne I learned a great deal and I have been still digesting what I have learned. My main focus was desktop development and I was privileged to hang out with many great engineers from Sun and Authors of many books that I’ve only known virtually. Here are some photos during my time at the JavaOne 2009 Conference in San Francisco. I wish I had taken more photos, but its OK, I got a lot of videos with a very cool HD flip camcorder they gave me. Here are the many sessions and their slides that I have attended: Sun Developer Network / JavaOne / Java SE and Desktop However, I did get a chance to see and learn at least two server-side sessions too.

One of my main goals as an avid Java person (thanks to my two daughters) was to learn and meet the people who are the pioneers of JavaFX.  Another highlight of the day (day 2) was I got a chance to meet James Gosling which was an honor and privilege.

JavaOne Store

(not to be confused with the Java App Store)

One of the coolest things I’ve seen was the HTC diamond phone that was demonstrated and sold at the JavaOne Store. This is a full featured phone which contains Java ME/ JavaFX 1.2 which is demonstrated at Sergey Malenkov’s Blog. He has many JavaFX mobile apps demonstrated on the phone. I too bought this super duper cool phone. When I get some free time I will start playing with JavaFX mobile and blog about it.

I was one of the lucky ones to buy other stuff at the JavaOne store. It was pretty busy because people were just trying to buy up everything Java, Java, Java from t-shirts, pens, dukes, etc. As if it was the last JavaOne we will ever see. Actually it would be the last Sun sponsored one we’ll ever see. (but good news here is Scott & Larry’s keynote) . I guess this indicates how many developer folks continue to love all things Java no matter the economic conditions. (Kathy Sierra’s Blog entry about the JavaOne Store on July 04, 2005).

JavaOne Bookstore

John Griffin writes “Top Ten at JavaOne” on The Server Side about the top selling books at the JavaOne Conference Bookstore. Which the top two are ones that I have bought. One book that is worth mentioning is the “Pro JavaFX™ Platform: Script, Desktop and Mobile RIA with Java™ Technology” which did not make it on the shelves that day, However I got a chance to meet all four authors (Weiqi Gao, Dean Iverson, Stephen Chin, James L. Weaver) at the JavaOne Bookstore for a book signing. I have the e-book and waiting for my hard copy to be delivered.

1. JavaFX: Building Rich Internet Applications – Addison Wesley ISBN: 013701287X
2. Essential JavaFX – PTR (out June 11, 2009) ISBN: 0137042795

141-4109_IMG

I am still reading both books and will have more examples to show, so stay tuned.

Conclusion

I was happy to come home, but sad that it was over so quickly. Coming out of JavaOne I felt that there was a huge sense of a new beginning and that JavaFX Script/platform will be what early Java was meant to be (truly cross platform). Just witnessing JavaFX 1.2 running on a mobile device, TV settop box and the Desktop it simply tells me where the future of JavaFX will eventually move towards.  As consumers demand better user experiences and richer content I believe that Java/Sun was very wise to move in this direction. I can only hope that Oracle will embrace this technology and come out strong to compete with other RIA technologies.


JavaOne Minute

Introduction

Leading up to and during the JavaOne 2009 conference I will be assisting Sun in capturing interesting aspects of the conference. Please join me and others from Sun and watch exciting interviews with key developers and others like you. So, please keep a look out for me if you want to be interviewed. The quick video takes are called the JavaOne Minutes. Please check them out!

Disclaimer: I’m very new to the whole “In front of the camera experience“. I’m usually the one behind a camera. So, try not to get bored when watching me in the videos. I will have a tinge of Balimorese accent so you can laugh at me and laugh with me.

Another thing to note is that I have listed below all the media that I have done so far relating to JavaOne 2009. I will try to update this as I go along, but I will be on twitter. You can follow me at: http://twitter.com/carldea

JavaOne Contest entries:

Java Radio w/Chris Melissinos

JavaOne Minute

Problem

Too much to see at JavaOne.

Solution

  • Join me and others to try to capture JavaOne Minutes at the conference.
  • Laugh and enjoy the videos.
  • Share with the Java Community.

Java One Contest ‘Dude Where’s my Pass?’

Introduction

JavaOne Contest – ‘Dude Where’s my Pass?’

JavaOne is a conference that is held every year in California which show cases all the latest and greatest Java based technologies.  This year in 2009 I think it will be different. For starters Sun/Java was purchased by Oracle corp. Aside from business and any rumors, Sun still held awesome contests. One such contest is the JavaFX cash money prize. Another is the community held JavaFX micro challenges by Joshua Marinacci. And lastly, the JavaOne conference contest called ‘Dude, Where’s my Pass?‘ hosted by Chris Melissinos.

I have been a Java fan since the beginning and never had the opportunity to go to JavaOne. Hopefully, I will get a chance to attend JavaOne this year, by winning the contest. I’ve submitted two videos for the contest.

  1. Why my Daddy should go to JavaOne (click)
  2. A Quest for a Pass (click)

Problem

Try to win a trip and Pass to JavaOne at the Moscone Center (street view) in San Francisco California.

Solution

Have the right attitude no matter if you win or you lose. : )

Blast from a weird past… Oranges!

Introduction

To celebrate the JavaFX contest JFXStudio created a micro challenge or a mini contest. The challenge was to create something that is related to the word “Orange”.  I really wanted to play around with JavaFX and the Production Suite and currently didn’t have access to the latest Adobe Photoshop and Illustrator products which have the Save-As FXZ extension so I turned to open source. I used Inkscape to create an orange tree and saved it as plain SVG file.  I then used the Production Suite to convert svg file to a FXZ. This is nice because I can simply use the shapes as nodes in JavaFX.

orangetree

webstartbutton

My orange entry is reminiscent of a kid show that I grew up with called “H.R. Pufnstuf”. I know its very dated, and I’m not proud of it. So, back to the fun. Please click on approximately nine oranges and a magic button will appear. (Pressing it is safe). enjoy! If button doesn’t work cut and paste text to browser.

Update!

The surprise was a Youtube video of an episode of the “H.R. Pufnstuf” TV show. The poster of the video was in violation of copy right. Exerpt from Youtube: “This video is no longer available due to a copyright claim by DashGo/Audiobee”.

So, the demo still works just the scary and disturbing Witchy Poo video won’t be shown. My intent was to create an JavaFX RSS feed reader that would launch the browser if needed and Web page to be display.

Problem

How to do the “Designer / Developer workflow in JavaFX”?

Solution

  1. Use SVG designer tool (Illustrator, Photoshop, Inkscape)
  2. Use Production Suite to convert SVG files to FXZ files.
  3. Use NetBeans 6.5.1 to view and manipulate FXZs.
  4. Create a JavaFX project and use nodes from FXZ content.

Code:

Obtaining Graphical Assets

// obtain group from fxd id='orangeTree'
var fxdContent = FXDLoader.loadContent("{__DIR__}orangetree2plain.fxz");
var orangeTree = fxdContent.getGroup("orangeTree");

var allOranges:Node[] = [];
// get each individual oranges. id=orange1, id=orange2, etc.
for (i in [1..10]) insert fxdContent.getNode(“orange{i}”) into allOranges ;

Code: Displaying Group and other Nodes


Stage {
title: "Oranges! Oranges!"
width: 500
height: 500
scene: Scene {
content: [Text {
font : Font {
size : 16
}
x: 10, y: 30
content: "Oranges Smoranges"
},
orangeTree, youTubeLocation, witchyPoo
]
}
}

My Triangle Space Ship – JavaFX media sound

Introduction

I grew up with old arcade games such as Asteroids and thought about making a simple ship, yes the famous triangle in JavaFX. I had to dig up my old trigonometry book. Remember unit circles? Although, I have learned that in JavaFX there is an attribute called rotation it is important to know that it is in degrees, so converting them to radian measure is key to making your velocity correct. Please keep in mind there are simple optimizations for my calculation and would need refactoring. Another goal was to play sound effects. Click below to launch the demo. The objective is to fly around and shoot at the box on the left. My little triangle space ship has powerful missiles!

Update

The I do not have a place to host the media Sound files and the demo will not play the sound effects. I am still looking at a way to put into the jar file and use them.

My Triangle Space Ship

My Triangle Space Ship

Commands:

Left arrow – move left
Right arrow – move right
Up arrow – fly forward
Down arrow – stop
Space bar – Fire missles


Click here (JavaWebstart): Play My Triangle Space Ship

Problem

  1. Learn rotation
  2. play sound effects

Solution

  1. Rotation is a Float which is in degrees at a pivot point or center of a rectangular bounded region. But for triangles or polygons use the translateX and translateY or the centroid formula.
  2. Use JavaFX’s media

var missleLaunch = Media{
source: “demos/fxfun/my_triangle_ship/Missile_SE.mp3”
}

var missleHit = Media{
source: “demos/fxfun/my_triangle_ship/explosion2.mp3”
}
var player = MediaPlayer{
media: missleLaunch,
autoPlay: false
}

JavaFX Sprites and Animation

Introduction

Whenever I find time I try to play with game programming and AI. I have so many old books relating to game programming and noticed how often old algorithms and concepts still apply today. Many who start off with programming games will decide on the perspective or display type that the player will experience. Most people are familiar with platform games or also known as side-scroller type games (Mario Bros.).  I wanted to see how easy it would be to create something in JavaFX and so, over the weekend I put together a simple demo to demonstrate a simple side-scroller.  Thanks to Silveira Neto‘s blog site which helped me realize how easy animation was in JavaFX. To run the demo click the link below the image. The princess demo is my daughter walking and the background is her 3 foot doll house made to look 30 feet high! Click on the image to go to the blog entry.

Enjoy!

Commands:

left arrow key – walk left
right arrow key – walk right
up arrow key – freeze walking position
down arrow key – stand still

Princess Demo

Princess Demo

Click here to launch JavaWebstart of Princess Demo

The Problem

  1. Create a player sprite to be rendered and managed onto the game world
  2. Create a set of sprites.
  3. Create a game loop and game world

The Solution

  1. Create a class called Player
  2. Draw or take pictures of the character in the game
  3. Create a game world. Use JavaFX Timeline with keyframes to listen for key strokes, update sprites and render onto the scene.

Create a class called Player

public class Player extends ImageView {
    public-init var currentState:Integer;
    public-init var currentFrame:Integer;
    public-init var currentDirection:Integer;

    public function walkRight():Void {
        x += 7;
        currentDirection = 1;
        image = right[++currentFrame mod 9];
    }
    public function walkLeft():Void {
        x -= 7;
        currentDirection = -1;
        image = left[++currentFrame mod 9];
    }
    public function stand():Void {
        if (currentDirection == -1){
            image = standLeft;
        } else {
            image = standRight;
        }
    }
}

Create Sprites

I am not an artist and many sprites are often hard to get, so I decided to take pictures of my daughter in her PJs with a backpack and her doll house as the background of the game. My wife thought how strange it was while we were doing stop action photography. Ten images were snapped including her standing. Most of my time spent was creating transparent images. Next time I will use blue screen for easy background removal. Lastly I horizontally flip the images to make a set of images facing the other direction.

Creating the Game World

/*
 * Main.fx
 *
 * Created on Feb 14, 2009, 10:00:20 AM
 */

package carlfx2;

import carlfx2.player.Player;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

// keyboard
var    upkey = false; //
var rightkey = false; // go right
var  downkey = false; // stop
var  leftkey = false; // go left
var spacekey = false; // jump

// the ground
def ground = Line {
    startX: 0,
    startY: 200
    endX: 300,
    endY: 200
    strokeWidth: 1
    stroke: Color.GREEN
}

// house background
def house = ImageView{
    image: Image {
        url: "{__DIR__}images/background.png"
    }
};

// player sprite
var player = Player{
    x: 150
    y: 200 - carlfx2.player.standRight.height
    currentDirection:1
    currentFrame:0
    image:carlfx2.player.standRight
    onKeyPressed: function(e:KeyEvent){
        if (e.code == KeyCode.VK_DOWN) {
            downkey = true;
            upkey = false;
            leftkey = false;
            rightkey = false;
        } else
        if (e.code == KeyCode.VK_UP) {
            upkey = true;
            downkey = false;
            leftkey = false;
            rightkey = false;
        } else
        if (e.code == KeyCode.VK_LEFT) {
            leftkey = true;
            upkey = false;
            downkey = false;
            rightkey = false;
        } else
        if (e.code == KeyCode.VK_RIGHT) {
            rightkey = true;
            leftkey = false;
            upkey = false;
            downkey = false;
        }
        if (e.code == KeyCode.VK_SPACE){
            spacekey = true;
        }
    } // onKeyPressed
}

// game world / scene contents
var gameWorld = [house, ground, player];

// game loop
var gameLoop = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames: KeyFrame {
        time: 1s / 10
        action: function() {
            // todo: check collision before next move
            if(rightkey) {
                player.walkRight();
            }
            if(leftkey) {
                player.walkLeft();
            }
            if(downkey) {
                player.stand();
            }
        }
    }
}

gameLoop.play();

// game stage
Stage {
    title: "Princess Demo",
    width: 400,
    height: 250
    visible: true
    scene: Scene{
        fill: Color.BLACK
	content:gameWorld
    }
}

Conclusion

This demonstrates how easy it is to render JavaFX artifacts.

I hope you will enjoy this little demo. Any comments are welcome.