0
votes

I am using a JTree in which new nodes needs to be inserted dynamically to the root(consider adding children to root). Once the user selects a node and clicks a button, the new node needs to be added after the selected node. If none of the node is selected then it adds the new node at the end of the tree. Below is my code

        public void addNodeToRoot(TestCase testCase) {
        DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(testCase.toString());
        int currentNoOfChildren = getTcBuilderTree().getModel().getChildCount(getTcBuilderTree().getModel().getRoot());
        TreePath currentSelection = getTcBuilderTree().getSelectionPath();
        int currentIndex=0;
        //if the user has not selected a node add the test case at the end of the tree
        if (currentSelection == null) {
            currentIndex = currentNoOfChildren;
        }
        //if user has selected a node then insert the new node after the selected node
        else {
                int[] currentSelectedIndex = getTcBuilderTree().getSelectionRows();
                currentIndex = currentSelectedIndex[0];

        }
        treeModel.insertNodeInto(childNode, getRoot(), currentIndex);
    }

it works all fine but the code gives an exception when there are child nodes in the level 3 as well. The reason is when the tree has more levels and when its expanded then the currentIndex gives unexpected number (it counts all the indexes in all levels up from the root to the selected node) and the app gives ArrayIndexOutOfBoundsException since the currentIndex becomes greater than currentNoOfChildren

If the tree is not expanded then everything happens correctly. Please let me know how to resolve this. Is there any other way to get the no of children of a specific level in the tree?

enter image description here

enter image description here

1

1 Answers

0
votes

Maybe code below can resolve your problem.

int currentNoOfChildren = getTcBuilderTree().getVisibleRowCount();