问题
Do i really have to implement the deep-clone myself or are there any library methods to get a deep clone of an JTree or it's TreeModel?
回答1:
As said by @SteveKuo, why do you need to clone a TreeModel
? TreeModel
can be shared amongst different instances of JTree
.
Here is a sample demo of two JTree's sharing the same model. Alternatively, you could create twice the same 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();
}
});
}
}
回答2:
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;
}
Just pass the root node and get the complete different root node and pass it to a new model of new tree.
回答3:
Why do you need to clone both JTree
and TreeModel
. JTree
is the view, which displays whatever the backing TreeModel
represents. If want to create a second identical tree, then you'd copy/clone the tree model, and create a new JTree
which points to the copied TreeModel
.
来源:https://stackoverflow.com/questions/13142290/easiest-way-to-clone-a-whole-jtree-treemodel