Universal Robots Forum

Insert Child node before the last current node

I am trying to insert a Child node before the last existing child node. For that, I am trying to use the InsertChildBefore() method, but it throws an exception.
getType() returns a String previously set in the node, in order to know which child node is the last one. It is returning “last” as expected, but later it crashes at root.insertChildBefore(root, programNode);

root.traverse(new ProgramNodeVisitor() {

@Override
public void visit(URCapProgramNode programNode, int index, int depth) {

        if(programNode.canGetAs(ChildNodeInterface.class)) {
  							
       String getNodeType = programNode.getAs(ChildNodeInterface.class).getType();
  							
       if (getNodeType == "last") {

        try {
  		root.insertChildBefore(root, programNode); //Here throws a TreeNode exception
            } catch (TreeStructureException e) {
                 e.printStackTrace();}
  }
        }
    }

});

Hi,

a bit more information about this would be good. is your root (TreeNode) the direct parent of your programNode?
also, inserting the referenced programNode while traversing right to another Position is bad and should be avoided.

Try using the locateDescendantTreeNode method of your rootTreeNode, copy your programNode and insert it in the desired position.

Hi,

Based on the API, locateDescendantTreeNode Gets a corresponding TreeNode instance for a child program node (a ProgramNode) in the sub-tree under this TreeNode.
However, I need just to insert a child from my main node, like I do properly with addChild, into specific position (previous to last existing).

More info: So I have,

Main Node -->
Child Node Last

And I need to:

Main Node -->
New inserted Child Node
Child Node Last

And the addChildBefote() is called from the Main Node.

Hi,

try sth. like this:

public void insertChildBeforeLastNode(){
    undoRedoManager.recordChanges(new UndoableChanges() {
        @Override
        public void executeChanges() {
            TreeNode last = rootTreeNode.getChildren().get(rootTreeNode.getChildren().size() - 1);
            ProgramNode newNode = programNodeFactory.createCommentNode();
            try {
                rootTreeNode.insertChildBefore(last,newNode);
            } catch (TreeStructureException e) {
                e.printStackTrace();
            }
        }
    });
}

however, i would prefer using the locateDescendantTreeNode method, as you don’t have to worry about correct indexing when having the ProgramNodeReference :wink: this would be an issue if your user inserts a node manually on the last position of your tree.

It woks perfectly. Thank you very much for your support.