将重复对象作为新行添加到 GridPane

Adding duplicate objects to GridPane as new row

我想根据文本字段中的输入数字动态添加新行。我已经在可见范围之外的 fxml(场景生成器)中准备了这一行(textField 和 comboBox)。

所以我参考了这些我想添加的对象:

@FXML
private ComboBox fieldType;

@FXML
private TextField fieldName;

并且根据来自其他文本字段的数字,我将行添加到 gridPane:

for (int i = 0; i < newRows; i++) {
    grid.addRow(grid.impl_getRowCount(), fieldName, fieldType);
}

我得到这个异常:

Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Children: duplicate children added: parent = Grid hgap=0.0, vgap=5.0, alignment=TOP_LEFT

我想我会像这样克隆这些对象:

public class CloningMachine implements Cloneable {

        private Node node;

        public CloningMachine() {
        }

        public CloningMachine setNode(Node node) {
            this.node = node;
            return this;
        }

        public Node getNode() {
            return node;
        }

        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }

for (int i = 0; i < newRows; i++) {
    grid.addRow(grid.impl_getRowCount(), ((CloningMachine)new CloningMachine().setNode(fieldName).clone()).getNode(), ((CloningMachine)new CloningMachine().setNode(fieldType).clone()).getNode());
}

但是我遇到了同样的异常。

有办法做到吗?谢谢

您的 CloningMachine 没有按预期工作。

Object.clone returns 对象的副本,其中所有数据 包括任何引用 都包含相同的数据。也就是说

((CloningMachine)new CloningMachine().setNode(n).clone()).getNode()

只是获得n的一种复杂方式,即

((CloningMachine)new CloningMachine().setNode(n).clone()).getNode() == n

总是产生 true.

The javadoc of Object.clone包含以下关于实现clone的句子。

Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies.

因此要正确实现克隆,您需要复制 Nodes "manually"(即使用构造函数创建一个新的并分配所有相关属性)。没有简单的方法解决这个问题。