2012-10-31 59 views
1

我正在創建一個編輯器應用程序,並且我的菜單有問題。在對象菜單中,我想使用JTree來顯示多個對象類型。這些對象類型是動態的插件註冊,並按照這種風格:從點分隔字符串列表中創建一個JTree

trigger.button 
trigger.lever 
out.door.fallgate 
trigger.plate 
out.door.door 
... 

這名單是未經分類的,我想建立一個TreeNode結構的JTree這樣的:

  • 觸發
    • 按鈕
    • 槓桿
      • fallgate

此外,如果用戶選擇的葉節點,我需要重新創建對象名稱(例如trigger.button)從TreePath。有人可以請告知如何做到這一點。

回答

2

在僞代碼,這是你需要做什麼......

public TreeNode buildTree(){ 
    String[] names = new String[]; // fill this with the names of your plugins 

    TreeNode tree; 

    // for each plugin name... 
    for (int i=0;i<names.length;i++){ 
     String currentName = names[i]; 
     String[] splitName = currentName.split("."); 

     // loop over the split name and see if the nodes exist in the tree. If not, create them 
     TreeNode parent = tree; 
     for (int n=0;n<splitName.length;n++){ 
      if (parent.hasChild(splitName[n])){ 
       // the parent node exists, so it doesn't need to be created. Store the node as 'parent' to use in the next loop run 
       parent = parent.getChild(splitName[n]); 
      } 
      else { 
       // the node doesn't exist, so create it. Then set it as 'parent' for use by the next loop run 
       TreeNode child = new TreeNode(splitName[n]); 
       parent.addChild(child); 
       parent = child; 
      } 
     } 

return tree; 
} 

這只是psuedocode - 您需要做適當實施TreeNode方法的工作,等等。親自嘗試 - 如果您還有其他問題,請創建一個問題並告訴我們您嘗試過自己動手,那我們會更願意幫你解決小問題。

+0

非常感謝你,這正是我所需要的。 – ShamanMaster

+0

沒問題。請記住如果您認爲它是最好的,請勾選此答案,以便其他人都知道您的問題已解決。 – wattostudios

+0

以下是從treePath中獲取對象名稱的另一種方法: public static String getElementName(TreePath path){ Object [] nodes = path.getPath(); String result =「」; //讀取路徑,從索引1開始,因爲我們不希望根 用於(int i = 1; i ShamanMaster

相關問題