Scroll the pane until line becomes visible in JScrollPane. - Java Swing

Java examples for Swing:JScrollPane

Description

Scroll the pane until line becomes visible in JScrollPane.

Demo Code


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

import javax.swing.text.JTextComponent;

public class Main {
    /**/*  w  ww. ja  v a  2 s . c  om*/
     * 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