Java Swing How to - JTree avoid collapse after reload








Question

We would like to know how to jTree avoid collapse after reload.

Answer

import java.awt.BorderLayout;
//  w ww .ja v  a2  s.  c  om
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class Main extends JPanel {
  JTree tree;
  DefaultTreeModel model;
  JButton btnAdd = new JButton("Add");
  int childCount;

  public Main() {
    super(new BorderLayout());
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");
    createNodes(top);

    model = new DefaultTreeModel(top);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(
        TreeSelectionModel.SINGLE_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    add(treeView);
    
    btnAdd.addActionListener(e->{
        TreePath treePath = tree.getSelectionPath();
        if (treePath != null) {
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath
              .getLastPathComponent();
          DefaultMutableTreeNode child = new DefaultMutableTreeNode("Child "
              + (++childCount));
          model.insertNodeInto(child, node, node.getChildCount());
        }
    });
    add(btnAdd, BorderLayout.SOUTH);
  }

  private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode book = null;

    category = new DefaultMutableTreeNode("Books for Java Programmers");
    top.add(category);

    book = new DefaultMutableTreeNode(new BookInfo(
        "Java Tutorial"));
    category.add(book);
    book = new DefaultMutableTreeNode(new BookInfo(
        "JDK"));
    category.add(book);
    book = new DefaultMutableTreeNode(new BookInfo(
        "GUI"));
    category.add(book);
    book = new DefaultMutableTreeNode(new BookInfo(
        "Guide"));
    category.add(book);

    book = new DefaultMutableTreeNode(new BookInfo(
        "Language"));
    category.add(book);

    book = new DefaultMutableTreeNode(new BookInfo(
        "SQL"));
    category.add(book);

    category = new DefaultMutableTreeNode("CSS");
    top.add(category);

    book = new DefaultMutableTreeNode(new BookInfo(
        "Spec"));
    category.add(book);

    book = new DefaultMutableTreeNode(new BookInfo(
        "Javascript"));
    category.add(book);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(new Main());

    frame.pack();
    frame.setVisible(true);
  }
}
class BookInfo {
  public String bookName;
  public BookInfo(String book) {
    bookName = book;
  }
  public String toString() {
    return bookName;
  }
}