I am using a Primefaces Tree which has a following structure :
Node 1
Node 1.1
Node 1.2
Node 1.3
Now, I want to add a node in betwee
This is another example which present a easy way to add now node below specific node.
XHTML
ManagedBean
@ManagedBean(name="treeBasicView")
@ViewScoped
public class BasicView implements Serializable {
private TreeNode root;
private TreeNode selectedNode;
private int position;
private String selectedNodeName;
private String newNodeName;
public TreeNode getRoot() {
return root;
}
public String getSelectedNodeName() {
return selectedNodeName;
}
public void setSelectedNodeName(String selectedNodeName) {
this.selectedNodeName = selectedNodeName;
}
public String getNewNodeName() {
return newNodeName;
}
public void setNewNodeName(String newNodeName) {
this.newNodeName = newNodeName;
}
@PostConstruct
public void init() {
root = new DefaultTreeNode("Root", null);
TreeNode node0 = new DefaultTreeNode("Node 0", root);
TreeNode node1 = new DefaultTreeNode("Node 1", root);
TreeNode node00 = new DefaultTreeNode("Node 0.0", node0);
TreeNode node01 = new DefaultTreeNode("Node 0.1", node0);
TreeNode node10 = new DefaultTreeNode("Node 1.0", node1);
node1.getChildren().add(new DefaultTreeNode("Node 1.1"));
node00.getChildren().add(new DefaultTreeNode("Node 0.0.0"));
node00.getChildren().add(new DefaultTreeNode("Node 0.0.1"));
node01.getChildren().add(new DefaultTreeNode("Node 0.1.0"));
node10.getChildren().add(new DefaultTreeNode("Node 1.0.0"));
root.getChildren().add(new DefaultTreeNode("Node 2"));
}
public void addNewNode(ActionEvent event) {
findNode(root);
selectedNode.getParent().getChildren().add(position, new DefaultTreeNode(newNodeName));
}
private void findNode(TreeNode node){
int pos = 0;
List subChild = node.getChildren();
for (TreeNode treeNode : subChild) {
pos = pos + 1;
if(treeNode.getData().equals(selectedNodeName)){
position = pos;
selectedNode = treeNode;
}
findNode(treeNode);
}
}
}
After click add child