Search code examples
javajavafxchildrenscene

How to get the elements on a scene JavaFX/Add objects to Scene dynamically


I have a scene - I want to pull all of the elements on that scene.

Basically, this is what I'm trying to create: A window with a button at the top that, when clicked, will "spawn" a new block on the screen that is draggable/interactable in other ways. I already have this down with blocks that I add in the code. But I want to make this dynamic, and for that, I need to be able to loop through all the objects on my scene, and I need to know how to add objects dynamically to the scene.

So, to make this clearer - I have two questions.

How do I add a rectangle or a circle or anything for that matter dynamically on the press of a button? How do I pull a list of all things on the scene. If I add rectangles, I want to be able to do something like scene.getElements() and have it return a list of elements on that scene so I can loop through them and check stuff about them.

My code:

final Circle circle = new Circle(200, 150, 50, Color.BLUEVIOLET);
final Rectangle rectangle = new Rectangle();
rectangle.setX(50);
rectangle.setY(50);
rectangle.setWidth(200);
rectangle.setHeight(100);
rectangle.setFill(Color.CORNFLOWERBLUE);
final Circle pizzaCrust = new Circle(SCENE_WIDTH/2, SCENE_HEIGHT/2, SCENE_WIDTH/2-150, Color.TAN);
final Circle pizzaInside = new Circle(SCENE_WIDTH/2, SCENE_HEIGHT/2, SCENE_WIDTH/2-160, Color.LIGHTYELLOW);
final Group group = new Group(pizzaCrust, pizzaInside, rectangle, circle);
final Scene scene = new Scene(group, SCENE_WIDTH, SCENE_HEIGHT, Color.WHITE);

Solution

  • Consider the Pane#getChildren method. You can loop in the list, and if you find a Pane, you can recursively call the method again.

    Be careful because not JavaFX elements are subclass of Pane.

    Note also that getChildren returns an ObservableList, so if you add an element to it, it will be shown on the stage.