DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. JavaFX in One Day

JavaFX in One Day

Anthony Goubard user avatar by
Anthony Goubard
·
May. 21, 09 · Interview
Like (0)
Save
Tweet
Share
13.56K Views

Join the DZone community and get the full member experience.

Join For Free

As written in my last blog, I've decided to look at other languages. Let's start with JavaFX.
I like developing user interfaces and I've already spent half a day learning it during an event organized by the nljug (Dutch Java User Group) more than 1 year ago.

Installation


Go to JavaFX.com.
Download the SDK 1.1 and install it.
When installing it you need to agree to a strange license (as already blogged last year about it):
If you don't have an Entitlement, or if your Entitlement doesn't cover additional software delivered to you, then such software is for your Evaluation Use

(a) Evaluation Use. You may evaluate Software internally for a period of 90 days from your first use.
If someone can explain what this means, please reply to this blog.
At the end of the install the register.html is shown (for me in Notepad :-) ).

NetBeans 6.5 (not 6.7 Beta) seems the IDE of choice when developing JavaFX. Other choices include Adobe Photoshop and Adobe Illustrator (that I don't have).
In Tools -> Plug ins, choose JavaFX Kit and JavaFX SDK. And restart the IDE

The language


The language tutorial is available at http://java.sun.com/javafx/1/tutorials/core/.

The keywords:

  • def, var, null
  • if, else, or, and
  • public, package, protected, public-init, public-read
  • bind, bound, on replace
  • step, insert into, delete [from], sizeof, before, after
  • for (in), while, break, continue, indexof
  • try, catch, finally
  • package, import, class, function, abstract, extends, override, return, new

Full list available here

Some explanations:

  • def is for constants and var for variables.
  • The default access modifier is private.
  • package is used to declare the package name and as access modifier.
  • public-init and public-read are used to indicate variables that can be publicly initialized or read. How to write the variable depends on the modifier that precede it (e.g. package public-read var x = 1;).
  • Operators are the same as in Java except for % replace by mod and ! repaced by not.
  • The language specification is available at http://openjfx.java.sun.com/current-build/doc/reference/JavaFXReference.html.
  • It looks like the class is written in JSON.

The main classes
The Java[FX]doc is available at http://java.sun.com/javafx/1.1/docs/api/. On the top right corner, you can specify for which profile you want the Javadoc. The common profile means work on Desktop (PC), Mobile and TVs.

  • String, Number, Integer, Boolean, Duration, Void
  • javafx.lang.FX, javafx.io.http.HttpRequest, javafx.util.StringLocalizer
  • javafx.stage.Stage, javafx.scene.Scene, javafx.scene.Group, javafx.scene.Node

Some explanations:

  • Number are translated to float in Java (since 1.1), so prefer Integer over Number when possible
  • Duration is used in animation, examples are 10s, 4ms, 0.5h.

Helloworld


Writing the app
In NetBeans: File -> New Project -> JavaFX -> JavaFX Application.
It generates code where you just need to replace "Application Title" and "Application content" with "Helloworld". And you can click the Run button.
Here is the code

Documentation
Right click on the project and click on Generate Javadoc.
It created a C:\Java\JavaFX\Test\examples\dist\javadoc directory but unfornately it's empty :-(.

Distribution
JavaFX is not a standard library in the sense that you cannot put it next to your Jar file, zip it and distribute it.
You're not allowed to distribute JavaFX.
To deploy as Applet:

 

<script src="http://dl.javafx.com/dtfx.js"> </script>
<script>
javafx(
{
codebase: "http://www.japplis.com/resources/blogs/javafx"
archive: "examples.jar",
draggable: true,
width: 250,
height: 80,
code: "examples.Helloworld",
name: "Helloworld"
}
);
</script>

 


Demo available here.

To deploy as Web Start:

In the dist directory , you will find 2 jnlp files, one for the Applet, one for the application (JFrame).
Make a copy of these files and replace some of the values like codebase, vendor, homepage, ...
click here to start it as application.

To deploy for mobile:
???

To deploy as an application:
Create an icon with javaws -Xnosplash helloworld.jnlp where helloworld.jnlp has codebase="file:///C:/Java/JavaFX/Test/examples/test" href="helloworld.jnlp".
The problem is that you can know in advance where the user will install the application and "." or "file:///." doesn't work as codebase.
Note that the created Jar file contains a Main-Class in its Manifest but java -jar helloworld.jar throws Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/javafx/runtime/FXObject

Remarks

  • JavaFX is shared among JavaFX applications.
  • The version of JavaFX is specified in the JNLP. Does that mean that my JavaFX app will use JavaFX 1.1 even if a more recent version is installed on the computer?
  • Dragging the Applet out of the browser didn't work for me.
  • Starting the application with JNLP, showed the warning sign next to the window.
  • Except Java developers, nobody knows what Web Start is.
  • You can also run the scripted .fx file (interpreted mode) and distribute the file compressed in GZip allowing a very small footprint

 

Concepts


Bindings
Binding is making a variable depend on the value of another variable.

var x = 10;
def y = bind x + 10; // y is always x + 10

You can bind types, objects, sequences, functions.

You can also use triggers with on replace which allow to notify a function when a variable is changed:


var x = 10 on replace oldX {
println("moving the object from {oldX} to {x}");
}

Sequences
Sequences are smart lists.
Initialisation:


var seq1 = [1, 2, 3, 4, 5];
var seq2 = [1..5];
// sequences can be created based on another sequence
var seq3 = seq2[n | n mod 2 == 0];
var seq4 = seq2[2..4]; // here 2 and 4 are the indexes of seq2 (not the values)

Use:
Just use then as you use arrays.
For comparaison of 2 sequences, use ==.

Manipulation
insert value into seq, insert value before seq[i], insert value after seq[i] to insert values.
delete value from seq, delete seq[i] to delete values.
reverse seq to reverse a sequence.

Classes and functions
So far our Helloworld example doesn't define a class or a function. But it uses the classes Stage, Scene, Text and Font.


class MyClass {
var myValue: String;
public function print() {
println("The value is {myValue}");
}
public function addText(text:String):String {
myValue = "{myValue}{text}";
return myValue
}
}

User Interface


One of the strong point of JavaFX is on writing user interfaces.

2D
Creation of 2D objects is based on Node objects that you put in Group in layouts.
Examples are Rectangle, Text, ImageView.

var rect1 = Rectangle { width:300 height: 150 };
var rect2 = Rectangle { x: bind rect1.x + 50 y: bind rect1.y + 50 width: 200 height: 50 fill: Color.RED onMouseEntered: function(e:MouseEvent) {rect1.fill = Color.BLUE} };
var group1 = Group { content:[rect1, rect2] };

Note that I've tried onMouseEntered: function(e:MouseEvent) {fill = Color.BLUE} but it didn't work.
Also gradient didn't work for me.

There is support for focus on nodes, and you have examples on how to do drag 'n drop with JavaFX.

Effects and animation

For effects all nodes have an effect variable. Effects seems to work only for the Desktop profile.
e.g.


group1.effect = Reflection { fraction: 0.7 };

Animation

JavaFX has a javafx.animation.transition package for standard transitions.


var rotTransition = RotateTransition {
duration: 3s node: group1
byAngle: 360
};
group1.onMouseClicked = function(e:MouseEvent) {
rotTransition.play();
}

To modify values (including colors) based on time you can use Timeline and maybe look at the dur and tween keywords.
Due to lack of time and failed attemps I'll skip this part.

Multimedia
One of the goodies that come with JavaFX is the MediaPlayer.
Create a Media then a MediaPlayer, put it in your scene with maybe some buttons to control it and enjoy.
Note that the user need to have the video/audio codec installed to work or you need to encode the video using ON2 FX encoder.

Controls
You have the standard Swing controls for the Desktop profile (using by default Nimbus Look and Feel).
But for the common profile you have only ImageView, Text and TextBox. No TabPanel, Checkbox, Button, ...
I advice you to look at JFXtras for more controls, layout but even there most of the classes are for the desktop profile.

Inputs
On Node you have functions like on onMousePressed or onKeyPressed.
I don't know how JavaFX handles multiple touch screens. Maybe for TVs it will handle the remote control like a keyboard.

Stages
As described before with JavaFX you create a Scene that you add in a stage. The device take this Stage to show to the user (like the Applet).
The Stage is used to defined application information such as title of the application, resizable, icon, ...
You can also define Stage extensions sush as AppletStageExtension.
Note that the height of the Stage seems to be the height of the JFrame which is the height of the Panel + ?? pixels.
I've tried

icons: [Image { url: "{__DIR__}examples/Duke.gif"} ]

 

but it didn't work. No wonder all JavaFX apps seem to have the same icon (the Java cup).

Other


When loading a file you can use {__DIR__} to indicate the URL root of the Jar file.
{__PROFILE__} can have the values browser, desktop or mobile.
{__FILE__} returns the URL of the current (class) file.

JavaFX is not supported on Linux.

The examples are quite oriented on shapes, effects and animation (JavaFX specialities). There is no Javadoc in the examples.

The API documentation is distributed with the SDK, other documentation is available online.

Interaction with Java (not tested)

Getting a Java class from JavaFX:

import mypackage.MyJavaClass;
var fxVar = MyJavaClass("Goodbye World!");

Getting a Java class from JavaFX:
http://java.dzone.com/tips/calling-javafx-java
JavaFX to and from JavaME: ??

Conclusion


Learning JavaFX (for 8 hours) is a lot of fun even if not everything is intuitive.
I don't see it as a generic language but more as a specific language to graphics (Logo++ ;-) ).
The size of the code is small, I can see JavaFX being used for online Ads, Mobile games (free for applets, small fee for mobiles) or multimedia players.
It will more be a competitor for JavaME than for Flash.

Pro's

  • Simple to learn
  • Readable
  • Media support
  • Animation
  • Binding
  • Write once, run everywhere extended to (billions of) devices

 

Con's

  • Mobile platform: No devices, no how to deploy, no effects, few controls.
  • Absolute dimensions mostly used in examples (not really portable to multiple devices with different screen sizes)
  • Mostly useful for applications using graphics

 

From http://www.jroller.com/agoubard
JavaFX mobile app Java (programming language) workplace

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Monolithic First
  • DevOps for Developers: Continuous Integration, GitHub Actions, and Sonar Cloud
  • Solving the Kubernetes Security Puzzle
  • mTLS Everywere

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: