Skip to main content

JavaFX Doodles: Doodle #1

Posted by joshy on February 6, 2008 at 5:09 PM PST

About four years ago when I started my blog I created a series of posts called Swing Hacks. This series eventually formed the basis of my similarly named book with Chris Adamson and led to my job at Sun. I think the series was successful. I still get an amazing number of hits to Swing Hacks 4, the Universal Right Click.

I wish I had carried the series longer, however, since there was probably much more I could talk about. So this is why I'm starting a new series for JavaFX that I'm going to call JavaFX Doodles. Each doodle will be a small example of code snippet that does something compact but useful. I will cover only JavaFX Script initially, then add mobile and designer tools later. Also note that I am using the currently available interpreter version of the JavaFX Script syntax. I will switch to the compiler version with a slightly different syntax when it becomes available (which shouldn't be too much longer).

I hope this series goes well and produces easily usable samples that will improve your own code. Let me know if there's anything you'd like to see a Doodle of. Here goes!

JavaFX Doodle #1

This is a simple demo I often use in my presentations. It uses basic binding and animation to create a grid of fading red cells.


Cells.fx in action

Most of this code is boilerplate. It declares a subclass of Rect called Cell which adds two attributes (the JavaFX Script term for properties): red and col. Then it creates a subclass of CompositeNode called RolloverGrid which returns a Group of 300 cells in a 30x10 grid. That's all pretty straight forward. I'll explain the interesting bits below.

package simpledemos;
import javafx.ui.*;
import javafx.ui.canvas.*;
import javafx.ui.filter.*;

import java.lang.System;
class Cell extends Rect {
    attribute red : Number;
    attribute col : Color;
attribute Cell.x = 0;
attribute Cell.y = 0;
attribute Cell.width = 20;
attribute Cell.height = 20;
attribute = 0.0;

//bind the red component of the color to the red attribute of the Cell.
// this will be auto-updated when ever the red attribute changes.
attribute Cell.fill = Color {
    red: bind red, green:0.0, blue:0, opacity: 1.0};

//animate the red attribute from 1 to 0 over 5 seconds, in 0.05 increments.
attribute Cell.onMouseEntered = operation(e) {
    red = [1.00,0.95 .. 0.00] dur 5000 linear; };

class RolloverGrid extends CompositeNode { }
operation RolloverGrid.composeNode() {
    var cells: Cell*;

    for(j in [0..10]) {
        for(i in [0..30]) {
            //insert a new cell into the cells list
            insert Cell { x: i*21, y: j*21 } into cells;
    return Group{ content: [Rect { x: 0, y: 0, width: 31*21, height: 11*21, fill: black},cells] };

Canvas { content: RolloverGrid { } }

There are two interesting parts to this code which do all of the work. The first is the initializer for the fill attribute (in bold above). It says that the fill attribute will be set to a Color composed of red, green, blue, and opacity components. Notice that green, blue, and opacity are set to constants (0,0 and 1, respectively). red, however, is set to bind red. This means it will be bound to the red attribute of the enclosing class, Cell. Because of this bind operation the red component of the fill attribute will be automated updated whenever the red attribute of Cell class changes.

The second important part is one line further down where the code sets an onMouseEntered handlers. In this operation it creates a animation for the red property. The code red = [1.00,0.95 .. 0.00] means 'make red go from 1 to 0 in steps of 0.05'. The dur 5000 part means to take 5000 milliseconds. The linear keyword says to animate linearly rather than with the default, which is a smooth in and smooth out (I'll describe these keywords in greater detail in a future blog).

Whenever the mouse enters a cell it will kick off an animation for that cell. The color will go immediately to bright red and then fade back to black (since the other components of the color are already 0). That's it! These two lines do all of the hard work to create an interactive animation.


You may have noticed a problem with this code. If you move the mouse in and out of a cell repeatedly within 5 seconds then then a new animation will start. There is no way to know if the animation is already running and optionally stop it. This is a limitation in the current animation system that is currently being overhauled by the compiler team. When the new syntax is ready I'll show you how to update to it.

To try out this code just paste it into an open JavaFX Script buffer into NetBeans 6 with the latest plugin (instructions for setting up NetBeans here)


Related Topics >>


joshy: C:\Documents and Settings\Administrator>javafx Files\Java\jdk1.6.0_02"" was unexpected at this time. the path is not full there, but it really doesn't matter. i checked the release date and it's way old :) so i downloaded old version. thanks for support

goddard: for now I recommend only running this in NetBeans 6 with the jfx plugin. We are updating JavaFX Pad to use the compiler and I *think* it will be released with the next milestone release of the compiler. When the compile and JavaFXPad are ready I will update my code to support the new animation syntax. The complier *should* run on Java 6, though. What problems are you having?

this example doesn't run well in javafxpad. it just displays black area in which the cells should be, but they're not. what is the best development tool for javafx? i've tried netbeans 5.5.1 with jfx plugin and opnejfx compiler. netbeans are slow for me and jfx compiler doesn't run on JRE 6. is there any plan to update javafxpad? (in case that's not continuously updated). thanks, jiri

I'm sorry I didn't respond to these questions right away. I've actually been traveling to California for meetings on JavaFX

alski: JavaFX is still very much a work in progress. Right now the NetBeans plugin is the most reliable way to run JavaFX Script code. This will change in the future as we get closer to the compiler and new runtime being released. We expect Applet support shortly as well.

raytucson: If you do Swing apps with lots of forms then FX Script likely will not impact you. FX script is for animation and graphics intensive applications, like are often done in Flash or Apple's Core Animation extensions. However, the rest of the JavaFX stack *will* affect you, like the new Applet plugin and deployment toolkit which will make getting Java installed and running both faster and easier than ever before.

mikeazzi: I'll look around for some brushed metal code and work on a blog about it.

varan: It's true that FX Script does not support varargs. I don't know if that will change. If you join the compiler mailing list you can talk to the guys working on the language itself.

psychostud I have some more demos coming that show transitions and animations. Stay tuned.

kishoresjava: The designer tool is going to take a long time to bring to 1.0. After all, Adobe's designer tools are all at least a decade old. We don't want to rush this to market. However, at JavaOne we will show you how to easily pull graphics created by designers using traditional design tools into your JavaFX applications.

Any updates about the Designer Tool ? I am eagerly waiting for the Designer Tool. can anyone know how long we may need to wait to see the Designer ? Kishore.

Josh, I think one of the things which swing lacked was combinig animation with component behaviour ..
.i hope javafx helps us to acheive this easily...please can u show us some examples of using javafx with effects(move,fade,bounce) which are triggered on any component events like click,show,add etc

JavaFX is a lot of fun. While porting the the Pagelayout layout manager to JavaFx I realized that JavaFx does not allow variable number of arguments to methods or functions. Is this correct? It's not a big deal, as one can always use an array of objects as an argument.

Thanks Josh for the demo. I do however have a sort of unrelated question. Would you happen to have handy a JavaFX example that shows how to paint brushed metal background colors? If you do, I would really appreciate it if you could provide it. Thanks.

I'm sort of with alski. I've been coding with Swing since 2001. How does a Swing programmer get started with JavaFX. Why would I switch. Should I switch. Will JavaFX have a more compelling deployment experience than WebStart. Please blog about these issues. Why would a Swing guru use JavaFX?

@alski Thats because its still in development. When Java 6 update N actually comes out you will see the combination of fast starting Applets, small install jvms, JavaFXScript and the scene graph and effects technology come together into something more like what you are looking for.

I'm a bit baffled. If JavaFX is supposed to be some sort of "Flash killer", why is it that all the samples I ever see require me to launch JavaFxPad from Web Start. Your blog doesn't even show the sample in action, it just shows the that because it's impossible at this time to get it reasonably working from a web page short of an applet of web start? The whole JavaFX experience to me feels extremely disjointed so I tend to completely ignore it. What's the real end goal for the technology?