Thursday, April 29, 2010

Back Off, Steve

I cannot express my indignation adequately in 140 characters.
Apple has published a well-written open letter from Steve Jobs about the iPhone/iPad vs Flash kerfuffle.
Being used to the JVM, I will admit that the Flash Player does not seem as fast or robust. But I do find it to be a fairly pleasant development environment. And it is very good at what it was designed for.
The real problem I have with the open letter is the last, most important reason Jobs lists. It boils down to: we just want to protect our developers from making bad choices (as defined by us). By force if necessary. This is just so wrong for so many reasons.
If Apple wants to ban the Flash Player from their platforms, fine. But don't try to dictate what languages developers can use under the guise of "supporting open standards." Apple, if the use of ActionScript leads to inferior applications, they will be killed off by the native applications. The point is: fair competition should always be allowed to determine the winner.
If Adobe's tools make it easy for developers to create nice applications that people want to use, you do everyone a disservice by imposing additional artificial restrictions on your already closed-garden app store. Stop hindering free competition!
I really enjoy developing applications on my brand new MacBook Pro. But my next mobile device is going to be powered by a little green robot. Not because I want to make a statement. Just because I want to be able to decide how to write applications for my own device. And for me personally, neither Objective-C nor HTML5 are appealing choices.
Just my worthless opinion. We now return to our regularly scheduled JavaFX addiction.

Tuesday, April 27, 2010

So What's It All Good For?

Ok, so my previous post (which I refer to facetiously as the Encyclopedia of JavaFX Styling) was a tad on the long-ish side. It contained a lot of not-so-trivial-to-understand information. It contained information that was biased toward helping control authors understand the new system rather than application developers.

So I can certainly understand the reactions of some folks: "Holy cow that looks complicated!" or "Why should I learn all of that?" or "What's this new-fangled system even good for?". The reason application developers should learn the new styling system is very simple: you can now do things with a few lines of CSS that used to take many lines of JavaFX code.
Like all of JavaFX, it's all about developer productivity!
Let's say as an application developer you decided that:
  • All of your application buttons should be round, or
  • Your checkboxes should have red X's rather than black checks and the text associated with them should turn red when the checkbox is selected, or
  • You want an awesome slider for your "number of gold stars" rating system complete with a star-shaped thumb bar that casts a drop shadow! (Really? Ok...).
Pre-JavaFX 1.3 you would be doing some combination of styling and overriding skin classes and rewriting skin code. Now with JavaFX 1.3, all of this is just a style sheet away.
.scene {
    -fx-font: 16pt "Amble"
}

.button {
    -fx-base: dodgerblue;
    -fx-shape: "M 50,30  m 0,25  a 1,1 0 0,0 0,-50  a 1,1 0 1,0 0,50";
    -fx-scale-shape: false;
}

.check-box:selected *.label {
    -fx-text-fill: red
}

.check-box:selected *.mark {
    -fx-background-color: red;
    -fx-shape: "M 0,0 H1 L 4,3 7,0 H8 V1 L 5,4 8,7 V8 H7 L 4,5 1,8 H0 V7 L 3,4 0,1 Z";
}

.slider *.track {
    -fx-base: derive( goldenrod, 50% );
}

.slider *.thumb {
    -fx-shape: "M 50,5 L 37,40 5,40 30,60 20,95 50,75 80,95 70,60 95,40 63,40 Z";
    -fx-background-color: derive(goldenrod,-50%), goldenrod;
    -fx-background-radius: 0, 0;
    -fx-background-insets: 0, 2;
    -fx-padding: 10;
    -fx-effect: dropshadow( two-pass-box , rgba(0,0,0,0.6) , 4, 0.0 , 0 , 1 );
}

Just apply this style sheet and BLAM! All your buttons are round, all your checkboxes are X'ed, and all of your sliders are golden. Life is good. Behold.

simpleskinning.png

Although... we may want to re-think that red checkbox label. Ick.

Monday, April 26, 2010

Advanced JavaFX Control Styling

JavaFX v1.3 includes a brand new and much more powerful CSS-based styling and skinning engine. This article will take a peak under the covers and show you how to get the most out of JavaFX styling so you can develop a unique look for your applications. I'll even show you how to do some basic re-skinning of the core controls - changing not just their color scheme but also their shape! - all from the comfort and convenience of your style sheet. That is a lot of ground to cover so we better get started.

Understanding Regions

Warning!! The Region API is not public and is not considered a finished work. It can, and certainly will, change in future versions. Maybe even in JavaFX v1.3.1. The code presented here is for demonstration of the concepts underlying the new styling system in JavaFX 1.3. If you are considering using this information to build your own custom controls, be sure you understand the down side of using private APIs!

In v1.3 the core controls are made up of regions. Regions are basically a shape with one or more backgrounds and borders. All core control skins inherit from SkinBase which extends Region. Take the LabelSkin as an example. Its inheritance hierarchy looks like this:

LabelSkin -> SkinBase -> Region -> Stack

So the controls are regions, but they can also have zero or more sub-regions. Think of a scroll bar control. It is a region, but it also has sub-regions for the thumb button, the track, and the up and down arrow buttons.

Regions are tied into the new CSS system and can be fully specified, right down to their shape, from a style sheet.

Note that SkinBase does not inherit from Skin at any point. A SkinBase can be assigned to a custom control's skin variable through the use of the SkinAdapter class. The SkinAdapter will take care of passing along the control and behavior assignments to the SkinBase when SkinAdapter is set as the Control's skin.

Creating a Demonstration Control

I simply define a class that extends Control, assign the skin using the SkinAdapter, and override the styleClass variable.

public class DemoControl extends Control {
    // This is the class I'll use in style sheets
    override var styleClass = "demo-control";

    // SkinAdapter lets me use a Region as a Skin
    override var skin = SkinAdapter {
        rootRegion: DemoControlRegionSkin{}
    }
}

Next I define a Region-based skin by creating a class that extends SkinBase.

public class DemoControlRegionSkin extends SkinBase {
    // SkinAdapter will set up SkinBase's control and behavior vars
    var cc = bind control as DemoControl;

    // You should always give your control skins a default preferred size
    override function getPrefWidth( height ) { 100 }
    override function getPrefHeight( width ) { 100 }
}

JavaFX Styling Techniques

I think it's best to start with a basic example and build up from there. So I'll begin by creating a simple scene and adding our new demo control.

Stage {
    title: "JavaFX CSS Controls"
    scene: Scene {
        var stack:Stack;

        width: 300
        height: 300
        stylesheets: "{__DIR__}controlStyles.css"

        content: [
            stack = Stack {
                width: bind stack.scene.width
                height: bind stack.scene.height
                content: [
                      DemoControl {
                          layoutInfo: LayoutInfo {
                              width: 250
                              height: 250
                          }
                      }
                ]
            }
        ]
    }
}

I created a simple Scene that is 300 by 300 pixels and has a Stack container that fills it completely. I then created a new instance of my DemoControl and set it's preferred width and height to be 250 pixels. Note that this will override the preferred width and height of 100 that I entered into the control skin itself when I added those functions. By default a Stack will size its children to their preferred size and center them. Therefore, when this program is run we should see a 250 by 250 rectangle (a.k.a. a square) centered in the scene. I'll now add some minimal styling in controlStyles.css (which is added to the Scene above) so the Region's rectangle will be visible.

.scene {
    -fx-font: 16pt "Amble";
    -dean-slightlydarkergreen: derive( green, -25% );
}

.demo-control {
    -fx-background-color: skyblue;
    -fx-border-color: -dean-slightlydarkergreen;
    -fx-border-width: 2;
}

This small style sheet first sets a default font for the Scene. I haven't added any controls with text yet, but I will later and it's always nice to set these things up in one place. Below the font attribute, I demonstrate a feature of JavaFX styling: the ability to derive a new color from an existing one and store it for later use. In this case, I created a darker version of Green and named it -dean-slightlydarkergreen. Not only am I now immortalized in my own style sheet, but the DemoControl can reference this attribute later as shown above for the control's border color. Note that I use the same class string "demo-control" that I hard-coded into my DemoControl class. Let's see how this looks so far.

Gradients

You can also specify linear gradients in your style sheet. The image and code below shows a fancier version of the DemoControl.

#gradient.demo-control {
    -dean-lightnavy: derive(navy, 100%);
    -dean-navygrad: linear (0%,0%) to (100%,0%) stops (0%, -dean-lightnavy) (100%, navy);
    -fx-background-color: linear (0%,0%) to (0%,50%) stops (0%, derive(deepskyblue, 80%)) (30%, deepskyblue) reflect;
    -fx-border-color: -dean-navygrad null -dean-navygrad null;
    -fx-border-width: 8 0 8 0;
}

You can see by the CSS selector "#gradient.demo-control" that this style will be applied to DemoControls with "gradient" for an ID. I didn't have to change any JavaFX script code to make this work other than adding the id: "gradient" attribute to the DemoControl's object literal declaration in the Scene, thereby picking up this new style.

In this style, I also derive a new light navy color and then reference it again when I define my navy gradient (-dean-navygrad). This gradient is then used as the border color. I use it on the top and bottom while setting the left and right border colors to null. Similarly, I set the top and bottom border widths to 8 pixels while the left and right borders have a 0 width. Many style attributes of a Region have this ability to specify top, right, bottom, and left properties individually. On the other hand, if I were to simply say "-fx-border-width: 8" then all borders would be 8 pixels wide.

The Region's background color is a slightly more complicated linear gradient. It goes half way down the rectangle and is then reflected so the bottom half matches the top. Note that you can even embed "derive" functions inside of linear gradient definitions. More power!

Multiple Backgrounds

As I said at the beginning, Regions are made up of a shape and one or more backgrounds and borders. Let's take a look at how you define multiple backgrounds and borders for your region. Once again, I will make no changes to our source code other than the control's ID in the scene and a new style in the style sheet.

#multibg.demo-control {
    -fx-background-color: skyblue, mediumaquamarine;
    -fx-background-radius: 15 0 15 0;
    -fx-background-insets: 0, 20;
    -fx-border-color: navy, darkcyan;
    -fx-border-style: dotted;
    -fx-border-width: 2;
    -fx-border-radius: 15 0 15 0;
    -fx-border-insets: 0, 20;
}

Most of the style attributes of a Region can take multiple items in their declarations. You can see examples of this in the declarations of the -fx-background-color, -fx-background-insets, and the -fx-border-color attributes. In these cases, the first item is applied to the first background, the second item is applied to the second background and so on. Therefore we end up with a skyblue rectangle with navy border and a medium aquamarine rectangle with a dark cyan border. The first background has no insets (it is filled right to the border of the control), while the second rectangle is inset by 20 pixels on all sides.

In cases where there are multiple backgrounds but only one item specified, the first item will be applied to all backgrounds. For example, both rectangles have top-left and bottom-right rounded corners defined by the -fx-background-radius and -fx-border-radius attributes. Since only one set of radius attributes are defined, it will be applied to both backgrounds.

The thing to remember is that commas separate multiple items in a single attribute (as in the two items specified by -fx-background-color above), whereas spaces are used as the separators in an item that can take multiple values (as in the one item having 4 values specified by -fx-border-radius above). Crystal clear? Good. Let's take it up a notch.

Getting Fancier

Here's a twist: many of those attributes that can take multiple values in a single item (like -fx-border-radius) can also take multiple items. This allows you, for example, to specify a different set of border radius values for each background.

#multibgoppcorners.demo-control {
    -fx-background-color: skyblue, mediumaquamarine;
    -fx-background-radius: 15 0 15 0, 0 15 0 15;
    -fx-background-insets: 0, 20 40 20 40;
    -fx-border-color: navy, darkcyan;
    -fx-border-style: dotted, dashed;
    -fx-border-width: 2, 1;
    -fx-border-radius: 15 0 15 0, 0 15 0 15;
    -fx-border-insets: 0, 20 40 20 40;
}

Here I specify a completely different set of values for the -fx-background-radius, -fx-background-insets, -fx-border-radius, and -fx-border-insets attributes for each background. Remember, multiple values within a single item are separated by spaces while multiple items are separated by commas.

Styling Conclusions

In this section I've experimented with the most common style attributes that are used on Regions. You can also use the regular Node style attributes that I covered here. Of interest will be Node's -fx-opacity, -fx-effect, and -fx-cursor attributes. It should also be noted that Regions have a corresponding set of attributes for image-based backgrounds and borders (i.e. -fx-background-image and -fx-border-image and so on). I'm not going to cover them here, but I would expect Oracle to publish full documentation on these attributes very soon.

Shaping Controls

So far, I've just used the default rectangular shape but by using the style sheet I can make a region take on just about any shape that can be imagined. The shape of a Region is specified using SVG path notation. This notation uses a compact encoding to describe shapes using a series of commands and coordinates. Commands are represented by a single letter. For example, M is the move-to command. If the command letter is upper case then the coordinates that follow are considered absolute coordinates whereas the coordinates are interpreted as relative if the letter is lower case. So "M 0 1" means move to location 0,1 while "m 0 1" means move 1 unit in the y direction from the current location. See this page for details of the SVG path syntax.

Movement and Lines

Drawing shapes with one or more lines is extremely easy. The format of the commands is shown in the following table.

Move toM x y m x y
Line toL (x y)+ l (x y)+
Horizontal line toH x
Vertical line toV y
Close the current pathZ z

Suppose I wanted a triangular region instead of the default rectangle.

#line.demo-control {
    -fx-shape: "M 0,1 L 1,1 .5,0 Z";
    -fx-background-color: skyblue, blue;
    -fx-background-insets: 0, 20 20 10 20;
}
The coordinate system used in these paths is the same one used in JavaFX: x increases to the right, y increases down. So our shape is defined as:
  1. Move down one unit in the y direction
  2. Draw a poly-line to the coordinate 1,1 and then 0.5,0
  3. Close the path
By the way, the use of commas to separate the x,y coordinates in a SVG path command are purely optional. I like to use them because it makes the command more readable to me. I'm using capital letters so those coordinates are absolute, not relative to each other. By default, the shape is scaled to fill the area of the control, so the scale of the coordinates doesn't matter. I could have just as easily used 0, 50, and 100 rather than 0, 0.5 and 1.0. You can see that even though the shape has changed, our ability to specify multiple backgrounds with offsets hasn't. One thing to watch our for is that, with non-rectangular shapes, the insets may need to be adjusted to keep the inner shape centered. Here I had to adjust the bottom inset of the second background to make the triangles look centered. I don't know if this is a bug or a feature, but for JavaFX 1.3 be aware that you may need to play with the insets to get things to look exactly as you want. And although the coordinates of the shape are scaled, the insets are still specified in pixels.

Cubic Curves

The SVG path commands for drawing cubic Bezier curves are shown in the following table.

Cubic Bezier curve to Draws a curve from the current point to x,y. x1,y1 is the control point at the beginning of the curve. x2,y2 is the control point at the end of the curve.C (x1 y1 x2 y2 x y)+ c (x1 y1 x2 y2 x y)+
Cubic Bezier curve to (shorthand) Draws a curve from the current point to x,y. The control point at the beginning of the curve is the reflection of the second control point from the previous curve. x2,y2 is the control point at the end of the curve.S (x2 y2 x y)+ s (x2 y2 x y)+

So let's take a look at a region shaped with cubic curves.

#cubic.demo-control {
    -fx-shape: "M100,200 C100,100 250,100 250,200 S400,300 400,200 Z";
    -fx-background-color: skyblue, blue;
    -fx-background-insets: 0, 10;
}
This is admittedly a somewhat fanciful shape for a control. It is important to note that the control's clickable area still takes up the whole 250 by 250 pixels even though the Region's backgrounds take up a smaller area.

Quadratic Curves

The quadratic Bezier curve commands are shown in the table below.
Quadratic Bezier curve to Draws a curve from the current point to x,y. x1,y1 is the control point of the curve.Q (x1 y1 x y)+ q (x1 y1 x y)+
Quadratic Bezier curve to (shorthand) Draws a curve from the current point to x,y. The control point at the beginning of the curve is the reflection of the control point from the previous curve.T (x y)+ t (x y)+
Let's take a look at a quadratic curve example.
#quadratic.demo-control {
    -fx-shape: "M0,200 Q100,50 200,200 T500,100";
    -fx-background-color: skyblue, blue;
    -fx-background-insets: 0, 10;
}
The shape of our region just keeps getting more interesting!

Elliptical Arcs

The arc command is easily the most confusing of the SVG path commands. Use of SVG graphical editors is highly recommended!
Elliptical arc to rx ry - The radius of the resulting arc x-axis-rotation - Rotation of the x in degrees large-arc-flag - If 1 then the largest arc between the start and end points will be drawn. If 0 then the smallest are will be drawn. sweep-flag - Indicates the direction in which the arc is drawn. A 1 specifies the positive direction, a 0 specifies the negative direction. x y - The end point of the resulting arc. These are absolute coordinates or are relative to the start point (the current location) depending on whether the A or a command is used.A (rx,ry x-axis-rotation large-arc-flag sweep-flag x,y)+ a (rx,ry x-axis-rotation large-arc-flag sweep-flag x,y)+
What are arcs good for? Lot's of things, of course, but circles are an obvious choice. However, drawing a circle with arc commands is not as trivial as you would imagine. Here is an example.
#arc.demo-control {
    -fx-shape: "M 50,30  m 0,25  a 1,1 0 0,0 0,-50  a 1,1 0 1,0 0,50";
    -fx-background-color: skyblue, blue;
    -fx-background-insets: 0, 10;
}
As you can see, you actually need to define two arcs: one for each 180 degree ellipse.

Final Thoughts on Shapes

The ability to change, not just the colors, but the actual shapes of the regions that make up the core controls gives application developers unprecedented control over the look of their applications. Need a slider with a gold star for the thumb track? Easy. Buttons that look like clouds? Very do-able. The only limit is your imagination. Just remember, as with many of the things that JavaFX makes easy for developers: with great power comes great responsibility!

Using Caspian Styles

One last thing I want to address is the subject of using that styles in caspian.css with your own controls. The Caspian class in JavaFX 1.2 contained several nice utility functions that would generate nice gradients that tied into the Caspian theme. That class no longer exists in JavaFX 1.3. To use the Caspian theme with your own controls, you will need to use the values defined in the caspian.css style sheet.

Let's return to the DemoControl and make it look like it fits in with the Caspian controls.

#caspian.demo-control {
    -fx-background-color: -fx-body-color;
    -fx-background-radius: 5;
    -fx-border-color: null;
}

As you can see, all I've done is use the -fx-body-color attribute from caspian.css as my background color, added a corner radius to match Caspian's, and turned off the border I would normally inherit from the default demo-control style. In order for the -fx-body-color attribute to be defined, the caspian.css has to be loaded into the scene. Instantiating any core control will take care of this. In this case, I not only instantiated a button, but I also added it to the scene's Stack container just for comparison.

Adding Borders

Now I'll go the whole nine yards and add Caspian-style borders as well. I can take these right out of the button style in caspian.css.
#caspianborders.demo-control {
    -fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
    -fx-background-radius: 5, 5, 4, 3;
    -fx-background-insets: 0 0 -1 0, 0, 1, 2;
    -fx-border-width: 0;
}
Here I have actually defined four different backgrounds for the DemoControl's region. The insets are used to make sure they appear properly as a shadow, two borders and the body. Using the Caspian-defined attributes for body, border and shadow color means that my DemoControl will respond to changes in the application-defined -fx-base attribute. This is the attribute you would set if you wanted to change the base color of all Caspian controls in the entire application. I can set -fx-base to a new color in the .scene style and both DemoControl and the button will pick up the change.
.scene {
     -fx-font: 16pt "Amble";
     -fx-base: dodgerblue;
}

Final Conclusion

I really like the power and flexibility of the new CSS support in JavaFX 1.3. Styling and skinning controls is now easier than ever. If you need to, you can create an entirely unique look for your application without having to change any lines of JavaFX source code. It brings us a true separation of presentation and program logic. All in all, I give it a gold star. A gold star button even!
#star.button {
     -fx-shape: "M 50,5 L 37,40 5,40 30,60 20,95 50,75 80,95 70,60 95,40 63,40 Z";
     -fx-base: goldenrod
}

References

I found these things handy while learning about all of this:
  1. The caspian.css style sheet located in com/sun/javafx/scene/control/skin/caspian/caspian.css in the javafx-ui-controls.jar packaged with the JavaFX SDK.
  2. The Style Editor example at: http://www.javafx.com/samples/StyleEditor/index.html

Thursday, April 22, 2010

A Brief Introduction to Styling Controls in JavaFX 1.3

Support for styling the core controls using CSS has been greatly enhanced for JavaFX 1.3. In fact, the default skin for the core controls, called Caspian, is now written as a style sheet rather than in JavaFX Script code. Below is an example of a small JavaFX 1.3 style sheet that I wrote for Jim Weaver's 3D Calendar application:

.scene {
   /* default font for all content, inherited by all nodes */
   -fx-font: 16pt "Amble Cn";

   /* main color palette */
   -fx-base: #AEBBD2;
   -fx-accent: #385589;
   -fx-mark-color: #3E857C;
}

.text-box {
   -fx-effect: innershadow( two-pass-box, rgba(0,0,0,0.2), 10, 0.0, 0, 2 );
   -fx-text-fill: #385589
}

#title.text-box {
   -fx-font-size: 125%;
}

.button:strong {
   -fx-text-fill: #D3DAE9;
}

If you have used JavaFX's CSS support in previous versions, you will notice some changes in how style sheets are now written.

  • Where you used to write Scene, TextBox, and Button, you should now write .scene, .text-box, and .button. These are CSS class selectors, which kind of makes sense since you are selecting JavaFX control classes.
  • All JavaFX style attributes now start with the -fx extension in order to avoid conflicts with standard CSS attributes. For example, you should now write -fx-font rather than just font.
  • This style sheet also contains an example of one of the new features in JavaFX 1.3's style sheet support: the ability to an inner shadow effect. You can also specify a drop shadow using a similar syntax

Here is a table of some more new and fun attributes that can be set from style sheets.

Attribute Example Value(s) Works On Notes
-fx-cursor crosshair | default | hand | move | text | wait Nodes
-fx-opacity 0 .. 1.0 Nodes
-fx-rotate 0 .. 360 Nodes Defaults to 0. Not taken into account in layoutBounds
-fx-scale-x Number Nodes Defaults to 1. Not taken into account in layoutBounds
-fx-scale-y Number Nodes Defaults to 1. Not taken into account in layoutBounds
-fx-scale-z Number Nodes Defaults to 1. Not taken into account in layoutBounds
-fx-translate-x Number Nodes Defaults to 0. Not taken into account in layoutBounds
-fx-translate-y Number Nodes Defaults to 0. Not taken into account in layoutBounds
-fx-translate-z Number Nodes Defaults to 0. Not taken into account in layoutBounds
-fx-focus-color white | #FFEEDD | #FFF Controls Color of the focus outline
-fx-control-inner-background white | #FFEEDD | #FFF TextBox, PasswordBox, ListView
-fx-mark-color blue | #0000FF | #00F CheckBox, RadioButton, ScrollBar
-fx-echo-char "\u263A"; PasswordBox Make your password boxes friendly!

This is just a sample of some of the power of the new CSS support. I haven't even touched on linear and radial gradients, deriving colors using derive( pink, -20% ), the ladder function, or alternative ways of specifying colors: rgb(), rgba(), hsb(), and hsba(). So much left to cover!

Friday, December 11, 2009

Creating Custom Caspian Controls

Creating custom controls in JavaFX is not difficult. Creating custom controls that fit nicely with the default Caspian theme, with its pervasive use of gradients and animation, is a little trickier. This is only because the utility classes and methods that make it simple lie buried within com.sun packages that are not publicly documented. A little digging reveals a few gems that can be used to make your controls fit right in with the core JavaFX controls.
If you are observant, you will not fail to notice that this post also serves to emphasize some of the many reasons that I love, and love working with, Caspian.
Warning #1 This post is not an introduction to writing controls in JavaFX. I will not cover the basics of the Control - Skin - Behavior classes. A quick and simple tutorial on this topic can be found here.
Warning #2 All of the information in this post applies only to JavaFX 1.2.1. One of the dangers of using non-public classes is that they can change significantly from version to version (and they certainly will for JavaFX 1.3). If there is interest, I will update this information after JavaFX 1.3 is released.
Apology #1 I discovered the information I'm about to present here while writing my own controls. None of this should be considered official Caspian documentation since I do not work for Sun and I do not have access to their source code (but hopefully I will when they release the source someday). Everything here is accurate as far as I can tell, but I apologize if I have any of the details wrong. Hopefully someone from Sun will read this and let me know if I've made any mistakes.
Knock-knock Joke #1 (of 100) Knock, knock. Who's there? Yewben. Yewben who? Yewben warned, now on with the post!

Caspian 101 - Colors and Gradients

Caspian controls in JavaFX 1.2.1 all make use of a mixin class called Colorable. This mixin provides the ubiquitous base and accent properties that can be used to style the controls. The base property specifies the base color of the control while the accent property specifies the accent color on those controls that support it. ListView, for example, uses the accent property to specify the color with which it draws the selection highlight in the list. Usage of the Colorable mixin makes Caspian controls incredibly easy to style.
Two other colors are generated from the base color: the over color, which is used when the mouse pointer is over the control, and the pressed color, used when a control is (you guessed it) pressed. Caspian also generates five Paint objects from the base color: the body paint, the text paint, the border paint, the highlight line paint, and the shadow highlight paint. The screenshot below shows an application that displays these various colors and paints. It has been annotated with lines that show where they are used on a Caspian button (click the image to see a larger version).
If you launch the application, you can see that the button is a live control that has been scaled up to four times its normal size. If you hover the mouse cursor over the button or click on it, you will see the control's use of the over and pressed colors as well. Caspian is remarkably clever about generating nice looking controls from a single color.


The Caspian class in the com.sun.javafx.scene.control.caspian package provides easy access to these color-generating capabilities via module level functions:
  • Caspian.getOverColor( base: Color )
  • Caspian.getPressedColor( base: Color )
  • Caspian.getBodyPaint( base: Color )
  • Caspian.getTextPaint( base: Color )
  • Caspian.getBorderPaint( base: Color )
  • Caspian.getHighlightLinePaint( base: Color )
  • Caspian.getShadowHighlightPaint( base: Color )
Therefore, the first step in creating a control that fits in with the native Caspian controls is to use the Colorable mixin class and use it's base property to generate the other colors for your control.
public class MyControlSkin extends Skin, Colorable {

def bodyPaint = bind Caspian.getBodyPaint( base );
def overPaint = bind Caspian.getBodyPaint( Caspian.getOverColor( base ) );
def pressedPaint = bind Caspian.getBodyPaint( Caspian.getPressedColor( base ) );

var mousePressed = false;

def background = Rectangle {
   fill: bind {
       if (mousePressed) {
           pressedPaint
       } else if (background.hover) {
           overPaint
       } else {
           bodyPaint
       }
   }
   stroke: bind Caspian.getBorderPaint( base )
   blocksMouse: true
   onMousePressed: function( me: MouseEvent ) {
       mousePressed = true;
       // ... may also need to notify the Behavior ...
   }
   onMouseReleased: function( me: MouseEvent ) {
       mousePressed = false;
       // ... may also need to notify the Behavior ...
   }
}

// ... I'm too modest to show more skin ...
}
   
With just a few lines of code you get nice Caspian gradients for your control plus your custom control will respond to the same base style property as any core JavaFX control. In this simple example I only changed the body paint in response to mouse events. The core JavaFX controls also tend to update their border and highlight colors in response to hover and pressed events. You can see this when you run the Caspian Colors application above and interact with the button.

Caspian 102 - Animated State Transitions

Getting the colors and gradients right is only half the battle. Caspian also uses nice animated transitions when the control changes its state. For instance, when a button is disabled it doesn't just flip to a disabled state, it animates the transition with a smooth fade of the button's opacity. Similar animations occur when a control gets enabled, gains or loses focus, gets hovered over, or gets clicked. Caspian provides a smooth and fluid user experience.
This is something I want to support in my own controls since I am a subscriber to the Chet Haas school of thought regarding the positive role that good, subtle animation cues can play in a user interface. Animating all of those state transitions could become a real chore, so it's a good thing that you can cheat and take advantage of the hard work already done by the team at Sun. Allow me to introduce you to the States, State, and StateTransition classes. All of these little beauties are found in the com.sun.javafx.animation.transition package.
The State class allows you to define each state of your control. The class has four properties of interest:
idThe name of the state.
defaultState Should be set to true if this state is the one in which your control starts.
active Should be set to true when this state is active. Normally this will be bound to some property of the control. For example, when defining the "hover" state, you would bind the state's active property to the skin node's hover property.
priority An integer value that is used to establish precedence when multiple states are active at the same time.
The StateTransition class derives from Transition and allows you to define the animation that will occur when your control moves from one state to another. The properties of interest in this class are id, fromState, toState, and animation. The fromState property is a string that allows you to specify the id of the state you are transitioning from. Likewise for the toState property.
And finally, the States class keeps track of your control's states and manages the transitions between them. The following code shows an example of the states and transitions for a custom control.
def FAST_TRANSITION = 250ms;
def SLOW_TRANSITION = 500ms;

public class MyControlSkin extends Skin, Colorable {
override var color = base;  // color is another property defined in Colorable

def over = bind Caspian.getOverColor( base );
def pressed = bind Caspian.getPressedColor( base );

var mousePressed = false;

def states = States {
   states: [
       State { id: "disabled", active: bind control.disabled }
       State { id: "armed",    active: bind mousePressed }
       State { id: "hover",    active: bind control.hover }
       State { id: "enabled",  active: bind not control.disabled, defaultState: true }
   ]
   transitions: [
       StateTransition {
           id: "Enter-Enabled"
           toState: "enabled"
           animation: ParallelTransition {
               content: [
                   ColorTransition {
                       colorable: this
                       toValue: base
                       duration: SLOW_TRANSITION
                   }
                   FadeTransition {
                       node: bind node
                       toValue: 1.0
                       duration: FAST_TRANSITION
                   }
               ]
           }
       }
       StateTransition {
           id: "Enter-Hover"
           toState: "hover"
           animation: ColorTransition {
               colorable: this
               toValue: over
               duration: FAST_TRANSITION
           }
       }
       StateTransition {
           id: "Enter-Armed"
           toState: "armed"
           animation: ColorTransition {
               colorable: this
               toValue: pressed
               duration: FAST_TRANSITION
           }
       }
       StateTransition {
           id: "Enter-Disabled"
           toState: "disabled"
           animation: FadeTransition {
               node: bind node
               toValue: 0.33
               duration: FAST_TRANSITION
           }
       }
   ]
}

// ... Move along, nothing more to see ...
}
   
True to the spirit of JavaFX's declarative syntax, all you have to do is declare your states and the transitions between them and the rest is handled for you! You can't ask for easier animations than that.
In addition to those shown above, many controls also have "focused", "focused+hover", and "focused+armed" states defined as well (along with their corresponding transitions). Note that I did not specify any priorities in the State declarations above. That is because the order in which the states are declared establishes a default priority. You only need to specify an explicit priority if you want to override this default. Also note that I didn't specify a fromState in any of my state transitions. I was telling the States class that it can use that transition when entering the target state from any other state. You only need to specify a fromState if you want the transition to be used only when entering a state from one other particular state.
This code makes use of another Caspian gem, the ColorTransition class which is found in the com.sun.javafx.scene.control.caspian package. It will animate the Colorable mixin's color property from one value to another. This is yet another reason to make use of the Colorable mixin in your code - easy color animations!

The Etched Button Control

This control was created because I wanted a close button for the XPane control that looked like it was etched into the background of the title bar. I wanted the etched button to fit in as closely as possible with the other Caspian controls as well. The resulting control is shown in the image below.

The button features animations for over and pressed states as well as the disabled state. There are a few other nice features as well. The button can display text or a graphic, or both. It can optionally apply an etched effect to its content. The effect is similar to the one Jasper shows in a recent blog post.
Clicking on the disable check box will disable both the etched button and the normal Caspian button. You can also compare their over and pressed animations to verify that they are a close match. This control shows that it is possible to match the look and feel of the Caspian controls very closely by simply using some of the classes that are provided with the standard JavaFX runtime.

P.S.

Knock, knock. Who's there? Yewer. Yewer who? Yewer afraid I was going to tell 100 knock-knock jokes weren't you!

Wednesday, December 2, 2009

Kids + Robots = FUN!

Every year from August to December, somewhere between 90 and 99.9 percent of my free time is taken up as a volunteer helping to organize the Poudre Qualifier, a regional FIRST LEGO League robotics tournament. FIRST LEGO League (or FLL) is a robotics competition for teams of kids from 9 to 15 years old. At the Poudre Qualifier, we host over 300 kids on 48 teams. These kids have spent the last 2 months (or more) building a robot using a LEGO MindStorms robotics kit and creating a research project. Their robot will try to do as many missions as possible on a 8-foot by 4-foot playing field in two and a half minutes.
Of all of the FIRST (For Inspiration and Recognition of Science and Technology) robotics competitions, FLL is unique in that the robot is completely autonomous. It must be smart enough to go out and accomplish its missions and return to base all on its own. If the kids have to rescue the robot out on the table they incur a penalty. Here is a video of a robot doing its thing during a past competition. The kids also do a research project based on the theme of that year's competition. Recent themes have included nanotechnology, energy, and transportation. At the tournaments, a team presents their research project to a panel of experts. Teams are also judged on a technical interview, where they answer questions about their robot's design, construction, and programming; as well as a teamwork exercise to test their ability to solve problems as a team.
With well over 100,000 kids on over 15,000 teams all over the world, FLL is a terrific program for getting young people interested in science and technology in an exciting and fun way. By talking to and learning from experts, kids find out that they can use science and technology to make a positive difference in their world. They also learn many valuable life skills for a future engineer or scientist: teamwork, public speaking, being interviewed, working and performing under the pressure of deadlines, and most of all, how to compete while treating teammates and opponents with respect and courtesy. That is a concept called Gracious Professionalism and it is the core value of FIRST.
What FIRST really needs is volunteers who want to share their passion for science and technology with a new generation of enthusiasts. So my request to you, dear reader, is to find a FIRST event near you and volunteer! Be a referee, a judge, a coach... whatever you want. Just get involved! It will only cost you a few hours or a day, and I guarantee that you will have an amazing time. All of the FIRST events are free and open to the public, so you can also come out and watch these kids having a great time solving difficult problems. If you live here in Colorado, we have the state championship tournament coming up. Information can be found here. And by the way, more photos from our tournament can be found here.

Friday, October 2, 2009

JavaFX Interview

The folks at Sun were kind enough to ask me to visit with them about one of my favorite subjects: JavaFX.
Check it out if you're so inclined.