2012-10-30 51 views

回答

0

爲什麼你需要克隆JTreeTreeModelJTree是視圖,它顯示任何後盾TreeModel代表。如果想要創建第二個相同的樹,那麼您需要複製/克隆樹模型,並創建一個指向複製的TreeModel的新的JTree

1

正如@SteveKuo所說,你爲什麼需要克隆一個TreeModelTreeModel可以在JTree的不同實例之間共享。

下面是兩個JTree共享相同模型的示例演示。或者,你可以創建兩次相同TreeModel

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTree; 
import javax.swing.SwingUtilities; 
import javax.swing.Timer; 
import javax.swing.tree.DefaultMutableTreeNode; 
import javax.swing.tree.DefaultTreeModel; 

public class Test2JTree { 

    private void initUI() { 
     final JFrame frame = new JFrame(Test2JTree.class.getSimpleName()); 
     final DefaultTreeModel model = getTreeModel(); 
     final JTree tree1 = new JTree(model); 
     final JTree tree2 = new JTree(model); 
     frame.add(new JScrollPane(tree1), BorderLayout.WEST); 
     frame.add(new JScrollPane(tree2), BorderLayout.EAST); 
     frame.pack(); 
     frame.setSize(frame.getWidth() + 50, frame.getHeight() + 140); 
     frame.setVisible(true); 
     Timer t = new Timer(2000, new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); 
       root.add(new DefaultMutableTreeNode("A new node")); 
       model.nodesWereInserted(root, new int[] { root.getChildCount() - 1 }); 
       tree1.expandRow(0); 
       tree2.expandRow(0); 
       frame.revalidate(); 
      } 
     }); 
     t.start(); 
    } 

    private DefaultTreeModel getTreeModel() { 
     return new DefaultTreeModel(new DefaultMutableTreeNode("Root object")); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new Test2JTree().initUI(); 
      } 
     }); 
    } 
} 
+0

謝謝你的例子。問題是,它想要回收一棵老樹並清除所有樹葉,所以我只剩下文件夾。但是從共享模型中移除葉子也會更改原始樹。所以我正在考慮一個簡單的克隆作爲這個簡單的方法... – ghandi

+0

@ghandi你如何建立你的TreeModel在第一個地方?你可能有某種「工廠方法」,你可以再次調用並刪除所有的「葉子」。 –

0

public IndigoMutableTreeNode cloneNode(IndigoMutableTreeNode node){ 
 
\t \t IndigoMutableTreeNode newNode = new IndigoMutableTreeNode(node.getUserObject()); 
 
     for(int iChildren=node.getChildCount(), i=0;i<iChildren; i++){ 
 
       newNode.add((IndigoMutableTreeNode)cloneNode((IndigoMutableTreeNode)node.getChildAt(i))); 
 
     } 
 
     return newNode; 
 
    }

只是通過根節點,並獲得完整的不同根節點並把它傳遞給新樹的新模式。