Java Swing How to - Clone a whole JTree/TreeModel








Question

We would like to know how to clone a whole JTree/TreeModel.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from   w ww .ja v  a 2  s . co  m
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.Timer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class Main {
  private static DefaultTreeModel getTreeModel() {
    return new DefaultTreeModel(new DefaultMutableTreeNode("Root object"));
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame(Main.class.getSimpleName());
    DefaultTreeModel model = getTreeModel();
    JTree tree1 = new JTree(model);
    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();
  }
}