Java JScrollPane Scroll scrollToComponent(Component cmp)

Here you can find the source of scrollToComponent(Component cmp)

Description

scroll To Component

License

LGPL

Declaration

public static void scrollToComponent(Component cmp) 

Method Source Code

//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>
     * &lt;b&gt;root&lt;/b&gt;
     *   component
     *     component
     *       &lt;b&gt;child&lt;/b&gt;
     * </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;
    }
}

Related

  1. scrollComponentToEnd(JComponent c)
  2. scrolleable(final JComponent comp)
  3. scrollH(JComponent content)
  4. scrollRectLater(final JComponent comp, final Rectangle r)
  5. scrollRectToVisible(Component component, Rectangle aRect)
  6. scrollToVisible(int row, int col)
  7. scrollV(String title, JComponent content)
  8. scrollVertically(JComponent c, Rectangle r)
  9. scrollView(Component component)