JavaFX – Z-order of Nodes


Z-order is an ordering of overlapping two-dimensional objects, such as windows in a graphical user interface (GUI) or shapes in a vector graphics editor. One of the features of a typical GUI is that windows may overlap, so that one window hides part or all of another. When two windows overlap, their Z-order determines which one appears on top of the other. courtesy: wikipedia

JavaFX provides toFront() and toBack() methods in Node to change the Z-order. But users may want more control on how to order the nodes.

For Applet mode, click on above image

For standalone mode

In above sample, the Rectangles are stacked. The node is brought to top when user clicks on it. ActionScript provides DisplayObjectContainer.setChildIndex(child, index). Silverlight provides ZIndexProperty which can be set using SetValue method. Looks like its two different approach, one is done on Container and another on Node. So what is best way to address this in JavaFX? Here is an attempt…

In JavaFX, a sequence of Node is added to Group. So we could change the Z-order by sorting the sequence. This may be done using utility method – sort – available in javafx.util.Sequences.

The sort method is expecting an instance of java.lang.Comparable, for this we can create a CustomNode which implements Comparable and implement compareTo method. Also we can add an additional attribute zOrder. The comparison can be done based on this zOrder attribute. Please refer to NodeZ implementation for more information.

Now we can manipulate the Z-order by updating UI with node array returned by Sequences.sort(). The comparator may also be implemented based on various other attributes such as scale, translate, opacity etc. Yes, there may be some concern regarding updating of content in Group for every sort. What will be its implications? I need to perform some analysis on that, will try to share some info soon..

Try it out and let me know feedback and other options..

var dzone_style = ‘2’;

Advertisements