Scroll the JScrollPane until offset becomes visible. - Java Swing

Java examples for Swing:JScrollPane

Description

Scroll the JScrollPane until offset becomes visible.

Demo Code


//package com.java2s;
import java.awt.FontMetrics;
import java.awt.Point;
import javax.swing.JScrollPane;

import javax.swing.text.Element;
import javax.swing.text.JTextComponent;

public class Main {
    /**/*from w  ww  .  ja  v  a 2  s.  co m*/
     * Scroll the pane until offset becomes visible.
     * 
     * @param scroll
     * @param offset
     */
    public static void scrollToVisible(final JScrollPane scroll, int offset) {
        if (!(scroll.getViewport().getView() instanceof JTextComponent))
            return;

        JTextComponent txtCmp = (JTextComponent) scroll.getViewport()
                .getView();
        Element root = txtCmp.getDocument().getDefaultRootElement();
        int line = root.getElementIndex(offset);

        scrollLineToVisible(scroll, line);
    }

    /**
     * Scroll the pane until line becomes visible.
     * 
     * @param scroll
     * @param line
     */
    public static void scrollLineToVisible(final JScrollPane scroll,
            int line) {
        if (!(scroll.getViewport().getView() instanceof JTextComponent))
            return;

        JTextComponent txtCmp = (JTextComponent) scroll.getViewport()
                .getView();
        FontMetrics fm = txtCmp.getFontMetrics(txtCmp.getFont());
        int fontHeight = fm.getHeight();
        scroll.getViewport().setViewPosition(
                new Point(0, fontHeight * line));
    }
}

Related Tutorials