问题
I am trying to create a line on top of a circle.
Things that i have tried :
I added the circle to the StackPane, and then the StackPane and line to a group which i sent to the scene constructor got some undesired results like stackpane not spreading fully over the stage
adding the line after the circle puts it automatically above that but i need more control over it.
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
回答1:
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
- How to change order of children in JavaFX
来源:https://stackoverflow.com/questions/45089396/javafx-how-to-overlap-a-shape-onto-another