Java Swing How to - Refresh new JTree model








Question

We would like to know how to refresh new JTree model.

Answer

import java.awt.BorderLayout;
// w w  w  .  j a va2  s . c o  m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

public class Main extends JFrame {

  MyTreeModel jarFilesDB;
  JTree jtree;
  boolean isAlpha = false;
  JPanel contentPane = new JPanel();

  public static void main(String[] args) {
    Main frame = new Main();
    frame.setVisible(true);
  }

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);

    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    JButton btnNewButton = new JButton("Click Me");
    btnNewButton.addActionListener(e -> doClick());
    contentPane.add(btnNewButton, BorderLayout.NORTH);
    jarFilesDB = new MyTreeModel();
    jarFilesDB.load(isAlpha);
    isAlpha = !isAlpha;
    jtree = new JTree(jarFilesDB);
    JScrollPane scrollPane = new JScrollPane(jtree);
    contentPane.add(scrollPane, BorderLayout.CENTER);
  }

  private void doClick() {
    jarFilesDB.load(isAlpha);
    isAlpha = !isAlpha;
  }

}

class MyTreeModel extends DefaultTreeModel {

  DefaultMutableTreeNode rootNode = null;

  public MyTreeModel() {
    super(new DefaultMutableTreeNode("root"));
    rootNode = (DefaultMutableTreeNode) getRoot();
  }

  public void load(boolean isAlpha) {
    rootNode.removeAllChildren();

    String[] values;
    if (isAlpha)
      values = new String[] { "A", "A1", "A2", "B", "B1", "B2" };
    else
      values = new String[] { "10", "11", "12", "20", "21", "22" };

    DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(values[0]);
    DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode(values[1]);
    childNode.add(leafNode);
    leafNode = new DefaultMutableTreeNode(values[2]);
    childNode.add(leafNode);

    rootNode.add(childNode);

    childNode = new DefaultMutableTreeNode(values[3]);
    leafNode = new DefaultMutableTreeNode(values[4]);
    childNode.add(leafNode);
    leafNode = new DefaultMutableTreeNode(values[5]);
    childNode.add(leafNode);
    rootNode.add(childNode);

    nodeStructureChanged(rootNode);
  }

  public TreeNode getRootNode() {
    return rootNode;
  }
}