2016-03-15 138 views
0

我正在使用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給出意想不到的數字(它計算從根節點到所選節點的所有級別的所有索引),並且該應用給出ArrayIndexOutOfBoundsException,因爲currentIndex變成大於currentNoOfChildren

如果樹未展開,則所有事情都會正確發生。請讓我知道如何解決這個問題。有沒有其他方法可以讓樹中的特定級別的孩子沒有?

enter image description here

enter image description here

回答

0

也許下面的代碼可以解決你的問題。

int currentNoOfChildren = getTcBuilderTree().getVisibleRowCount(); 
+0

這是行不通的。它拋出同樣的例外。問題是存在與當前選定的索引不與孩子no – sher17

+0

哪種情況下導致異常? (節點選擇與否)。另一個問題:如果在級別3中選擇了一個節點,是否要將新節點添加到該級別或根級別?如果您想將其添加到級別3,則還必須更改父節點。 – rdonuk

+0

'當第二級節點具有子節點並且選擇最後第二級節點時'是異常拋出的位置。我使用兩個整數來獲取當前選定節點的索引以及根節點的子節點數。當樹與某些或全部子級摺疊時,當前所選索引會更改。回答你的第二個問題。當我選擇第三層節點並添加一個新節點時,當根或第二層節點被選中時,沒有任何事情發生(這是工作),然後新節點添加到根節點。我會嘗試在 – sher17