简体   繁体   English

如何获取场景中的元素JavaFX /将对象动态添加到场景

[英]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. 如果添加矩形,则希望能够执行诸如scene.getElements()之类的操作,并使其返回该场景中的元素列表,以便我可以遍历它们并检查有关它们的内容。

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);

Consider the Pane#getChildren method. 考虑Pane#getChildren方法。 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. 请注意,因为不是JavaFX元素是Pane的子类。

Note also that getChildren returns an ObservableList, so if you add an element to it, it will be shown on the stage. 还要注意,getChildren返回一个ObservableList,因此,如果向其添加元素,它将显示在舞台上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM