JavaFX: How to extend CustomNode properly
I have taken a look at custom controls before. Now it is time to examine how to extend CustomNodes.
In this post I take the same steps as before.
Empty CustomNode
Since 1.3 it is no longer necessary to implement any methods. So it is possible to create and use an empty class.
As expected the layoutBounds and boundsInLocal both have a width/height of 0.
CustomNode with a Rectangle
We add a Rectangle to our custom node. In the docs there are two possible ways described.
Overriding children var
The new, recommended way is to override the children var.
This way works as expected. The layoutBounds and boundsInLocal correspond to the bounds of the rectangle.
Overriding create()
This has been the old way to add children to a CustomNode. We just return the same rectangle.
And it works as expected.
(By the way: The default implementation of create() returns null).
Assigning children in init()/postinit()
But when there is a children var, why not simply assigning the children within the init method? So let’s try: Yes – works as it should. Bounds are calculated correctly. So I can’t tell you why the doc does not mention that way….
Adding two rectangles
No we add two rectangles as children that have different sizes and locations. The bounds contain both rectangles. This fact approves that a CustomNode has the same behavior as a Group.
Adding effects
Adding an effect to the rectangle
Adding an effect to the rectangle
Adding an effect (e.g. DropShadow) to the Rectangle changes both bounds. So CustomNode has the same behavior as a Group.
Adding an effect to the CustomNode itself
Adding an effect (e.g. DropShadow) to the CustomNode itself only changes the boundsInLocal. The layoutBounds only depend on the children. While this is the expected (and documented) behavior, it is good to see that it has been implemented correctly…
May 1st, 2010 at 15:24
[...] a CustomNode is quite easy. There are no gotchas, extending CustomNode and adding some children is enough. But of course that [...]
May 1st, 2010 at 19:07
That’s “Overriding create()”, not “Overriding createNode()”.
Otherwise, good article, inspecting various ways.
May 1st, 2010 at 19:44
Thanks. Fixed it