Ishan Srivastava
Ishan Srivastava

Reputation: 1189

JavaFX how to overlap a shape onto another

I am trying to create a line on top of a circle.

Things that i have tried :

e.g., i have 10 shapes and i want to declare them all and then decide what goes over what and i don't want to worry about adding them in order

Upvotes: 2

Views: 4755

Answers (1)

jewelsea
jewelsea

Reputation: 159290

How JavaFX paints

JavaFX uses a Painter's algorithm, painting the children of a Parent node in order from first to last, so that the last nodes will be painted over the first nodes.

This is done in a retained mode on every pulse rather than an immediate mode. So items are not painted until you relinquish control of logic to the JavaFX graphics system. That means that you can add the items to the scene graph and then reorder or move them around in the scene graph as you wish, before they are painted.

3D painting in JavaFX can also use Z-buffering, but this answer relates just to 2D painting of elements with the same z co-ordinate value, without Z-buffering.

How to set the paint order for nodes

By adding nodes to the children list of a parent, you can place your nodes in a Group parent or a Pane parent. The nodes will be painted in the order in which you added them to the children list.

A Pane is good if you wish to use CSS, otherwise a Group will usually do. Also a Pane has a resizable range, which a group does not. For these reasons, I usually prefer to use a Pane over a Group.

To change the order in which the children are painted, you can move nodes around in position within the children list.

For example, the following code will change the paint order of the first and fifth items in the parent pane children list:

Collections.swap(parentPane.getChildren(), 0, 4)

In addition, Node has toFront and toBack convenience methods to move a node to the back or front of the node's parent's child list.

Advice on layout pane usage

Don't use layout panes such as StackPane for holding nodes that you wish to explicitly position. Managed layout panes such as StackPane are designed to handle the layout of nodes automatically for you, according to an internal algorithm for the layout pane. For example, by default, every node you add to a StackPane will be centered in the middle of the StackPane.

Related

Upvotes: 8

Related Questions