Java Swing How to - Make JTree Select all nodes programatically








Question

We would like to know how to make JTree Select all nodes programatically.

Answer

import java.awt.Dimension;
//  ww  w  .j a  v a 2  s.c  o  m
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeSelectionModel;

public class Main {

  public static void main(String[] argv) {
    JTree tree = new JTree();
    tree.getSelectionModel().setSelectionMode(
        TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    int treeSelectedRows[] = { 3, 1 };
    tree.setSelectionRows(treeSelectedRows);
    TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {

      @Override
      public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
        JTree treeSource = (JTree) treeSelectionEvent.getSource();
        System.out.println("Min: " + treeSource.getMinSelectionRow());
        System.out.println("Max: " + treeSource.getMaxSelectionRow());
        System.out.println("Lead: " + treeSource.getLeadSelectionRow());
        System.out.println("Row: " + treeSource.getSelectionRows()[0]);
      }
    };
    tree.addTreeSelectionListener(treeSelectionListener);
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new JScrollPane(tree));
    frame.setPreferredSize(new Dimension(380, 320));
    frame.setLocation(150, 150);
    frame.pack();
    frame.setVisible(true);
  }
}