如何在JavaFX中的场景图中克隆节点? [英] How to clone a node in the scene graph in JavaFX?

查看:230
本文介绍了如何在JavaFX中的场景图中克隆节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有prefHeight = 70 //没有prefWidth或任何宽度的HBox ...

I have a HBox with prefHeight = 70 // no prefWidth or any width...

我还有一个具有prefWidth = 50 //不具有prefHeight或任何高度...

I also have a Pane with prefWidth = 50 // no prefHeight or any height...

我只想使用某个循环将窗格的多个实例添加到HBox。

I just want to add multiple instance of the pane to the HBox using some loop.

当我在循环主体中添加(窗格)时,会出现以下错误。

When I do add(pane) in the loop body it gives following error.

Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Children: duplicate children added: parent = HBox[id=myHBox]

I需要找到克隆窗格的方法(因为它按值传递)。
有人可以帮我吗?
(由于没有使用父项设置/计算窗格的prefHeight,因此无法使用快照)

I need to find way to clone the pane(as it passes by value). Can anybody help me please? (taking snapshot are not work for me because prefHeight of the pane is not set/ computed using parent)

推荐答案

发生此错误是因为您试图将节点相同实例添加到另一个 Node 。如果您从下面的示例中删除评论,那么您也会收到该错误。另一方面,循环会很好用,因为在每次迭代中都会创建一个新的 Button 实例。

This error happens because you're trying to add the same instance of a Node to another Node. If you remove the comments from the example below you'll get that error as well. Loop, on the other hand, will work fine because in each iteration new Button instance is created.

@Override
public void start(Stage stage) {
    FlowPane root = new FlowPane();

    // Results in error
    // Button b1 = new Button("Button");
    // root.getChildren().addAll(b1,b1);

    for (int i = 0; i < 4; i++) {
        Button b = new Button("Button");
        root.getChildren().add(b);
    }

    Scene scene = new Scene(root, 50, 100);

    stage.setScene(scene);
    stage.show();
}

您的窗格可能更复杂,但是您必须使用相同的原理。将负责创建窗格的代码放在单独的方法 getPane()等中,并循环使用它来获取新实例。

Your pane is probably more complicated, but you have to use the same principle. Put the code responsible for creating your pane in a separate method, getPane() or such, and use it in a loop to obtain new instances.

JavaFX并没有提供现成的解决方案来制作 Node 的深层副本。如果您的 Node 是静态创建的,则可以:

JavaFX doesn't give you an out-of-the-box solution to make a deep copy of a Node. If your Node is crated statically you can:


  1. 放入负责创建的代码它将它用一种单独的方法,并且每次需要获取窗格的新
    实例时,
    就会在整个应用程序中使用它。

  2. 在FXML文件中定义它,然后

如果您的 Node 具有由用户动态创建或修改的属性或子代。在这种情况下,您必须检查其元素并自行重新创建它们。

Things get significantly worse if your Node has properties or children that were created or modified dynamically by the user. In that case you have to inspect its elements and recreate them on your own.

这篇关于如何在JavaFX中的场景图中克隆节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆