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

问题描述 投票:0回答:3

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

java swing clone jtree treemodel
3个回答
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();
            }
        });
    }
}

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;
    }

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


0
投票

为什么你需要克隆JTreeTreeModelJTree是视图,显示TreeModel所代表的任何支持。如果想要创建第二个相同的树,那么您将复制/克隆树模型,并创建一个新的JTree,它指向复制的TreeModel

© www.soinside.com 2019 - 2024. All rights reserved.