Java JTree scroll to selection

Description

Java JTree scroll to selection

import java.awt.Point;
import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.JViewport;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class Main {
   public static void main(String[] args) {
      DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
      rootNode.add(a);/*from   w  w w  .  j a va 2 s .c o  m*/

      DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("1");
      a.add(a1);
      DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("2");
      a.add(a2);

      DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
      rootNode.add(b);
      DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("1");
      b.add(b1);

      JTree tree = new JTree(rootNode);

      tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
      
      scrollToSelection(tree);

      JFrame f = new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(new JScrollPane(tree));
      f.setSize(250, 250);
      f.setVisible(true);
   }

   public static void scrollToSelection(JTree tree) {
      if (!(tree.getParent() instanceof JViewport))
         return;

      setViewPortPosition((JViewport) tree.getParent(), tree.getPathBounds(tree.getSelectionPath()));

   }

   private static void setViewPortPosition(JViewport viewport, Rectangle position) {
      Point pt = viewport.getViewPosition();

      position.setLocation(position.x - pt.x, position.y - pt.y);

      viewport.scrollRectToVisible(position);
   }
}



PreviousNext

Related