Java Swing How to - Get depth of current node in JTree








Question

We would like to know how to get depth of current node in JTree.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
//w w w .j  av a  2s. co m
public class Main {
  public static void main(String args[]) {
    JTree tree = new JTree();
    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.add(new JScrollPane(tree));
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}