JavaFX Experiments – Order of Declaration Matters

Given the following piece of JavaFX Script

import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import java.lang.Math.sqrt;

class C extends CustomNode
{
    // Test #1: Commented out
    //var node: Group = Group {};

    protected override function create():Node
    {
        return node;
    }

    public var data:Number[] on replace olddata
    {
        for (item in data)
        {
            var side:Number = sqrt(item);
            insert Rectangle{
                width:side height:side
                stroke:Color.RED strokeWidth:2 fill:Color.TEAL
            }
            into node.content;
        }
    }

    // Test 2: Comment out
    var node: Group = Group {};
}

C { data: [21000, 10000]; }

One of these declares node at the end of the class, and the other declares it at the beginning of the class. Take a look at it for a while and see if you can guess the difference in behaviour?

Answer

The “on replace” trigger for data attribute does not throw an exception in Test #2 despite the fact that node is null.

Moral of the story

Order of initialization matters. Make sure you initialize variables before triggers are defined.

Bookmark and Share

You should follow me on twitter here

Comments are closed.