Here you can find the source of scrollToComponent(Component cmp)
public static void scrollToComponent(Component cmp)
//package com.java2s; //License from project: LGPL import java.awt.Component; import java.awt.Container; import java.awt.Point; import java.awt.Rectangle; import javax.swing.JScrollPane; public class Main { public static void scrollToComponent(Component cmp) { Container parent = cmp.getParent(); while (parent != null) { if (parent instanceof JScrollPane) { JScrollPane pane = (JScrollPane) parent; Point location = getRelativeLocation(pane.getViewport().getView(), cmp); Rectangle bounds = cmp.getBounds(); bounds.setLocation(location); pane.getViewport().scrollRectToVisible(bounds); pane.repaint();// w w w . j a v a 2s. c o m } parent = parent.getParent(); } } /** * Return relative location between root and child components. * * <pre> * <b>root</b> * component * component * <b>child</b> * </pre> * * Between root and child may contains other components, but root must be one of ancestor of child, or euals to child. * <p/> * This method differs from {@link Component#getLocation()} with compute relative location from specified parent element, but not direclty one only. * * @param root * Root of child * @param component * Child component * @return Location relative to specified root * @see Component#getLocation() */ public static Point getRelativeLocation(Component root, Component component) { if (root == null) { throw new IllegalArgumentException("root is null"); } if (component == null) { throw new IllegalArgumentException("component is null"); } Point location = component.getLocation(); while (!component.equals(root)) { component = component.getParent(); if (component == null) { throw new IllegalArgumentException("root is not ancestor of component"); } Point parentLocation = component.getLocation(); location.translate(parentLocation.x, parentLocation.y); } return location; } }