Jim has posted 66 posts at DZone. You can read more from them at their website. View Full User Profile

JavaFX SDK 1.0 is Here! Let's Build an App Together!

12.08.2008
| 13833 views |
  • submit to reddit

 

The long awaited 1.0 release of the JavaFX SDK is available, so I'd like to help you get up to speed by building an application with you.  Some upcoming posts in this blog will continue what we've started today, and along the way we'll work closely with expert graphic designer Mark Dingman of Malden Labs.  First, you need to get the JavaFX SDK:

Javafx_logo

Obtaining JavaFX SDK 1.0

Everything that you'll need to get started is freely available at javafx.com, so please go there and download the JavaFX SDK 1.0, bundled with NetBeans 6.5.  You can download it without NetBeans IDE, but there are a boatload of examples that you can easily build and run with NetBeans IDE.

Overview of the API Packages

Included in the JavaFX SDK download is the API documentation.  Take a look at this documentation, and then I'd like to give you a brief tour of the more commonly used API packages and classes, especially the ones that we're likely to use in the application that we build together.

The javafx.stage package contains a class named Stage, which is the top level of the UI containment hierarchy for any JavaFX application, regardless of where it is deployed (e.g. desktop, browser, or mobile phone).

The javafx.scene package contains some classes that you'll use often:

  • The Scene class is the second level of the UI containment hierarchy for JavaFX applications.  It in turn contains all of the UI elements contained in the application.  These elements are called graphical nodes, or simply nodes.
  • The Node class is the base class of all of the graphical nodes in JavaFX.  As you'll see, UI elements such as text, images, media, shapes, and controls (such as text boxes and buttons) are all subclasses of Node.  Take a moment to look at the attributes and functions in the Node class to appreciate the capabilities provided to all of its subclasses, including bounds calculation and mouse and keyboard event handling.
  • The CustomNode class enables you to create your own UI elements.  For some examples of creating custom nodes, see the JFX Custom Nodes category of this blog.  Please note that the JavaFX language syntax and API has changed somewhat since those examples were created, but they will serve as good reference for you.
  • The Group class is a subclass of the Node class whose purpose includes grouping nodes together into a single coordinate space, and allowing transforms (such as rotate) to be applied to the whole group.  Also, attributes of the group that are changed (such as opacity) apply to all of the nodes contained within the group.

There are several packages that begin with javafx.scene that contain subclasses of Node of various types.  For example:

The javafx.scene.image package contains the Image and ImageView classes, which enables images to be displayed in the Scene.  The ImageView class is a subclass of Node.

The javafx.scene.shape package contains several classes for drawing shapes such as Circle, Rectangle, Line, Polygon and Arc.  The base class of the shapes, named Shape, contains an attribute named fill that enables you to specify a color or gradient with which to fill the shape.

The javafx.scene.text package contains the Text class for drawing text in the scene.  The Font class enables you to specify the font name and size of the text.

The javafx.scene.media package has classes that enable you to play media.  The MediaView class is a subclass of Node that displays the media.

Although it doesn't begin with javafx.scene, the javafx.ext.swing package contains UI controls (such as SwingButton and SwingSlider) that subclass Node.  Many of the Swing "components" are available in this package, and because these components are actually nodes, any of the transforms and other capabilities of Node are available with these classes.  Also, any Swing components that aren't in this package may be used in JavaFX by wrapping them with the wrap function of the SwingComponent class.

The javafx.scene.control package is the way that UI controls in JavaFX are headed.  In the JavaFX SDK 1.0 there is just one control -- the TextBox class, but future versions will have more.  Each UI control will have the ability to be skinned, and styled via CSS.

The javafx.scene.transform package enables you to transform nodes (scale, rotate, translate, shear, and affine).

The javafx.scene.input package contains classes such as MouseEvent and KeyEvent that provide information about these events from within an event handler function such as the Node class' onMouseClicked event.

The javafx.scene.layout package contains a couple of layout nodes named HBox and VBox, which enable you to arrange nodes horizontally or vertically, respectively.  The spacing attribute on these classes specifies the space between the nodes.  I fully expect more layout nodes to be available in future versions of the JavaFX SDK, and you can write your own (like the simple TableNode that I created in an earlier blog post).  Also, there is an initiative underway by Stephen Chin and Keith Combs (the co-conspirators behind the WidgetFX project) called JFXtras.  This initiative will create useful JavaFX classes, including layout classes, that will augment what is available in JavaFX releases.

The javafx.scene.effect and javafx.scene.effect.light packages contain easy to use effects such as Reflection, Glow, Shadow and Lighting.

The javafx.animation and javafx.animation.transition packages contain time-based interpolations typically used for animation, and convenience classes for common transitions, respectively.

The javafx.io.http, javafx.data.pull, and javafx.data.xml packages provide a way to communicate with servers via HTTP, JSON and XML from any JavaFX enabled device (e.g. desktop and mobile phones).

Take a look at the JavaFX API docs again in the light of the information above to get a deeper sense for how you can use its capabilities.  Now let's write some code!

 

The Humble Beginnings of our Application

I've chosen a simple calculator as a good project to facilitate learning the JavaFX SDK 1.0, and here is the comp from our graphic designer Mark Dingman:

Calculator_comp

We'll take some baby steps by by writing code that creates some of the basic UI for the calculator.  Here's a screenshot of the first incarnation of our calculator application, missing a few essential keys.  Click on the Launch icon to run it as a Java Web Start application in its own window.

Simple_calc

Webstart.small2

 

Note: Before looking at the code for the simple calculator below, please note that some techniques used in this program are for teaching purposes only, and would not be used in a "real" program.  For example, the matrix of SwingButton controls is begging for a "for" expression which will be covered in a future incarnation of this program.

/*
* SimpleCalc.fx
*
* Developed 2008 by James L. Weaver (jim.weaver at javafxpert.com)
* to demonstrate creating applications using JavaFX SDK 1.0
* Please note that some techniques used in this program are for teaching
* purposes only, and would not be used in a "real" program. For example,
* the matrix of SwingButton controls is begging for a "for" expression
* which will be covered in a future incarnation of this program.
*/
package javafxpert;

import javafx.ext.swing.SwingButton;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextBox;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;

/**
* The "stage" for the application
*/
Stage {
var displayStr:String;
title: "Calculator"
width: 125
height: 165
scene: Scene {
fill: Color.BLUE
content: [
VBox {
spacing: 5
content: [
TextBox {
columns: 9
text: bind displayStr
editable: false
style: "border-radius:20;"
},
VBox {
content: [
HBox {
content: [
SwingButton {
text: "7"
action:
function():Void {
displayStr = "{displayStr}7";
}
},
SwingButton {
text: "8"
action:
function():Void {
displayStr = "{displayStr}8";
}
},
SwingButton {
text: "9"
action:
function():Void {
displayStr = "{displayStr}9";
}
},
]
},
HBox {
content: [
SwingButton {
text: "4"
action:
function():Void {
displayStr = "{displayStr}4";
}
},
SwingButton {
text: "5"
action:
function():Void {
displayStr = "{displayStr}5";
}
},
SwingButton {
text: "6"
action:
function():Void {
displayStr = "{displayStr}6";
}
},
]
},
HBox {
content: [
SwingButton {
text: "1"
action:
function():Void {
displayStr = "{displayStr}1";
}
},
SwingButton {
text: "2"
action:
function():Void {
displayStr = "{displayStr}2";
}
},
SwingButton {
text: "3"
action:
function():Void {
displayStr = "{displayStr}3";
}
},
]
},
]
}
]
}
]
}
}


Noteworthy Items in the Simple Calculator Program

The Overview of the API Packages section above should help you understand what is going on in the program.  There are a couple of concepts worth focusing on here:

  • Binding the UI to the model.  For example, the var named displayStr is a variable to which the text variable of the TextBox control is bound.  When one of the buttons is clicked, the anonymous function assigned to the action attribute of the SwingButton is called, which changes the value of displayStr.  Because of the bind, the text value of the TextBox is immediately updated.
  • Strings may contain expressions enclosed in curly braces, which, for example, is how string concatenation occurs in JavaFX Script.


Building the Simple Calculator Application

The JavaFX SDK 1.0 distribution provides for building JavaFX Script applications from the command line, or from the NetBeans IDE 6.5.  I've been using the IDE approach lately because NetBeans IDE generates the deployment code for you.  Go ahead and create a NetBeans IDE project using the File->NewProject wizard, and cut/paste the code from this post into a file named SimpleCalc.fx in a package named javafxpert.  Then in the Project Properties dialog, shown below, choose the Run category and then an Application Execution Model (such as Run in Browser).  When you run the application, it will run using the chosen execution model. 

Simple_calc_project_properties_run

You can control the dimensions of a JavaFX applet running a browser by visiting the Application category/page in the dialog above.  In that page you can also make decisions like whether to allow the user to drag the applet out of the browser, and whether to generate Pack200 compressed files that contain your application.

By the way, if you do decide to use the command-line tools, javafxc behaves like javac and javafx behaves like java.  The command-line parameters are the same between JavaFX and their Java counterparts.

Hope I didn't throw too much at you today, but I wanted to give you a jump start in developing JavaFX applications.  Please leave a comment if you have any questions.

Have fun!
Jim Weaver
JavaFXpert.com

Published at DZone with permission of its author, Jim Weaver.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Carl Dea replied on Mon, 2008/12/08 - 2:12pm

Jim,

 When I select Run in Browser it displays fine, but for some reason the mouse clicks don't work. Tabbing and hitting space bar works. I'm running XP using firefox and IE with no worky. I also noticed on Firefox the applet's upper right corner displays an ugly tab to block object. This may be due to AVG ad blocker or something. I have AVG for IE and it doesn't display 'block', but firefox it does.

Any thoughts?

 

-Carl

Magued Fouad replied on Mon, 2008/12/08 - 3:42pm

Had the same problem

Jacek Furmankiewicz replied on Mon, 2008/12/08 - 3:55pm

The first time I saw JavaFX a year ago I immediately disliked it's incredibly nested structure and now with larger code samples showing up, I think I like it even less.

Am I only the only finding this a pretty insane way to end a class? It's nested parentheses hell.

  1.                                                 displayStr = "{displayStr}3";  
  2.                                             }  
  3.                                     },  
  4.                                 ]  
  5.                             },  
  6.                         ]  
  7.                     }  
  8.                 ]  
  9.             }  
  10.         ]  
  11.     }  

 

 

Dmitri Trembovetski replied on Mon, 2008/12/08 - 4:14pm in response to: Jacek Furmankiewicz

Jacek, you don't have to write it this way, I think it's written like that more for brewity sake. It's no different than writing everything with anonymous classes in Java instead of defining separate listener classes, for example.

You can define a variable for each class, sequence, etc. It will look more readable then.

Dmitri

 

Jim Weaver replied on Mon, 2008/12/08 - 4:28pm

Carl,

Can you tell me what version of Java you're using, and send screenshots/console output?  I've not seen this one before with JavaFX Web-started applets.  Please send to jim.weaver [at] javafxpert.com

 

Thanks,

Jim Weaver

Carl Antaki replied on Mon, 2008/12/08 - 6:13pm

The examples on JavaFX.com are not written well. I see some of them are blocks of more than 200 lines of code. The demos are too slow, I think they should have waited for a month or so to refine the rough edges. Is it possible to refactor JavaFX code? I'll stick to Swing and will use JMC features. We need a tutorial on how to integrate JavaFX in a Swing App.

Carl Dea replied on Mon, 2008/12/08 - 10:26pm in response to: Jim Weaver

Jim,

Yep.. I can see why JavaFX is a lot easier than Swing. However, I am still wondering how does one with JavaFX able to use nice GUI controls like SwingX, Tabs, JTables, JTree, Look n Feel, etc.

Do people have to make these controls? Is this similar to JavaScript libraries for menus, slide-outs, etc. 

 

Regarding the problem I had earlier today:

I will send you the info. I really want to learn and help iron out the details. I played with the demo at work, and I would like to see if I can duplicate this at home. Another issue that I experienced was with two monitors the calculator window was black (when dragging the applet out of the browser on the secondary monitor) until I move it (across window boundaries) and it refreshes and repaires itself.

Will you be planning on making a second edition of your book?

 Thanks!

-Carl

GeekyCoder coder replied on Tue, 2008/12/09 - 12:02am

Carl Dea,

you might find it useful  to read through the release note as it highlight most issues working with JavaFX along with its workaround.

http://java.sun.com/javafx/1/reference/releasenotes/javafx-sdk-release-notes.html

 Among your case, the following issue is noted as 

"Issue: Movement of applets from one monitor to another in a multiple monitor configuration is not supported.

Description: JavaFX 1.0 SDK doesn't support multiple monitor configurations for some cases. When a browser running an applet is moved from one monitor to another, and the applet is then dragged out of the browser, repainting issues might occur.

Workaround: Move the applet back to the original screen. "

 

 

Carl Antaki,

"Is it possible to refactor JavaFX code? "

I do not think it is possible currently as refactoring of JavaFX is yet to support  in Netbeans.

WEll, is Intellij team listening :^) ?

 

 

Carl Dea replied on Tue, 2008/12/09 - 12:33am in response to: GeekyCoder coder

geekycoder,

 Thank you very much!

Reading... "It does a body good".

 -Carl

Jeroen Wenting replied on Tue, 2008/12/09 - 2:04am

That code looks to be an incredible mess, parenthesis hell indeed.
And it looks like every other bit of JFX code I've seen so far, which does not bode well.

Of course the defenders will come out and note that it's all generated anyway and all you ever need to do is click some buttons together in a visual designer in Netbeans, but we all know that's nonsense if you want to create any applications with more than very basic functionality (like, when you want buttons to actually do something useful).
I've had to work in languages requiring similarly convoluted constructs, and it's a real pain. Think the old TurboVision with its masses of nested constructors to create anything.

Walter Laan replied on Tue, 2008/12/09 - 5:57am

Is there an up to date Eclipse plugin?  The one at http://download.java.net/general/openjfx/plugins/eclipse/site.xml gives compile errors with the example posted.

 

Carl Dea replied on Tue, 2008/12/09 - 9:45am in response to: Jim Weaver

Jim,

The problem with the block tab is from the AdBlock in Firefox, it can simply be disabled, but it is annoying.
I'm probably answering my own questions and problems, but I hope that Sun and friends are aware of these types of things such as AdBlock Plus, etc.


I found out why the buttons don't click. This is based on the current bug from the release notes.

Steps to reproduce:
1) Move default browser window to secondary monitor.
2) In NetBeans 6.5 launch Applet so another tab will appear in browser.
3) Clicks aren't working.

Work Around:

Drag browser window from secondary monitor to primary monitor
Then the applet works fine.

-Carl

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.