Yes. The following adds to the children of root
.
root.getChildren().add( another );
Now the program is rearranged so that the scene graph is built in a method. The program builds the same scene graph as before, and draws the same picture as before.
import javafx.application.*; import javafx.stage.*; import javafx.scene.*; import javafx.scene.shape.*; import javafx.scene.paint.*; import java.util.Random; public class DrawNestedRectangles extends Application { double sceneWidth=400, sceneHeight= 300; double centerX=sceneWidth/2, centerY=sceneHeight/2; private void fillGroup( Group gr, double scale ) { double width=sceneWidth*scale, height=sceneHeight*scale; Rectangle rect = new Rectangle( centerX-width/2, centerY-height/2, width, height ); rect.setStrokeWidth( 2.0 ); rect.setStroke( Color.RED ); rect.setFill( Color.TRANSPARENT ); gr.getChildren().add( rect ); } public void start(Stage stage) { Group root = new Group( ); fillGroup( root, 0.9 ); Scene scene = new Scene(root, sceneWidth, sceneHeight, Color.GHOSTWHITE ); stage.setTitle("One Line"); stage.setScene(scene); stage.show(); } }
The start()
method creates a Group
object.
But initially the Group
has no children.
Then
fillGroup()
is called with a reference (pointer)
to the empty Group
.
It creates a rectangle and makes it a child of the Group
.
The parameters of the rectangle are calculated
based on the width, height, and center of the scene.
The parameter scale
adjusts the parameters so the rectangle fits into the scene.
In the above, the rectangle is 90% the size of the scene.
fillGroup( root, scale )
adds a rectangle to root
.
Any nodes already in the graph stay there.
Let's put a second rectangle inside the first. Modify the code to add a second rectangle to the group. Make it 80% the size of the scene.
public void start(Stage stage) { Group root = new Group( ); fillGroup( root, 0.9 ); Scene scene = new Scene(root, sceneWidth, sceneHeight, Color.GHOSTWHITE ); stage.setTitle("Two Calls to fillGroup"); stage.setScene(scene); stage.show(); } }