[英]How to get the index of the selected node in a selcted level in a JTree
我正在使用一個JTree,其中需要將新節點動態地插入到根中(考慮將子節點添加到根中)。 用戶選擇節點並單擊按鈕后,需要在所選節點之后添加新節點。 如果未選擇任何節點,則將新節點添加到樹的末尾。 下面是我的代碼
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);
}
一切正常,但是當級別3中也有子節點時,代碼也會給出異常。 原因是當樹具有更多級別並且展開時,currentIndex給出了意外的數字(它對從根到所選節點的所有級別的所有索引進行計數),並且由於currentIndex大於currentNoOfChildren ,應用程序給出了ArrayIndexOutOfBoundsException 。
如果樹沒有展開,那么一切都會正確進行。 請讓我知道如何解決此問題。 還有其他方法來獲取樹中特定級別的子代數嗎?
也許下面的代碼可以解決您的問題。
int currentNoOfChildren = getTcBuilderTree().getVisibleRowCount();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.