Get first visible line of the text component in a JScrollPane. - Java Swing

Java examples for Swing:JTextComponent

Description

Get first visible line of the text component in a JScrollPane.

Demo Code


//package com.java2s;
import java.awt.FontMetrics;

import javax.swing.text.JTextComponent;

public class Main {
    /**//from w  ww. j  av a  2s. com
     * Get first visible line of the text component in a JScrollPane.
     * 
     * @param txtCmp Text component.
     * @return The line.
     */
    public static int getTopLine(JTextComponent txtCmp) {
        FontMetrics fm = txtCmp.getFontMetrics(txtCmp.getFont());
        int fontHeight = fm.getHeight();

        return (Math.abs(txtCmp.getY()) + fm.getAscent()) / fontHeight + 1;
    }
}

Related Tutorials