简体   繁体   中英

How to get the index of the selected node in a selcted level in a JTree

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?

在此处输入图片说明

在此处输入图片说明

也许下面的代码可以解决您的问题。

int currentNoOfChildren = getTcBuilderTree().getVisibleRowCount();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM