克隆整个JTree / TreeModel的最简单方法是什么?

时间:2012-10-30 15:27:04

标签: java swing clone jtree treemodel

我是否真的必须自己实现深度克隆,还是有任何库方法来深入克隆JTree或它的TreeModel?

3 个答案:

答案 0 :(得分:1)

正如@SteveKuo所说,你为什么需要克隆一个TreeModelTreeModel可以在JTree的不同实例之间共享TreeModel

以下是两个JTree共享相同模型的示例演示。或者,您可以创建两次相同的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(); } }); } }

{{1}}

答案 1 :(得分:1)



public IndigoMutableTreeNode cloneNode(IndigoMutableTreeNode node){
		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;
    }
&#13;
&#13;
&#13;

只需传递根节点并获取完整的不同根节点,并将其传递给新树的新模型。

答案 2 :(得分:0)

为什么需要同时克隆JTreeTreeModelJTree是视图,显示支持TreeModel所代表的内容。如果要创建第二个相同的树,则复制/克隆树模型,并创建一个新的JTree,指向复制的TreeModel