Get number of rows in the content being shown in JTextComponent. - Java Swing

Java examples for Swing:JTextComponent

Description

Get number of rows in the content being shown in JTextComponent.

Demo Code


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

import javax.swing.text.JTextComponent;

public class Main {
    /**//from   www .j  av a2  s.  c om
     * Get number of rows in the content being shown. Independent of the text's
     * size.
     * 
     * @return Amount of rows.
     */
    public static int getRows(JTextComponent txtCmp) {
        FontMetrics fm = txtCmp.getFontMetrics(txtCmp.getFont());
        int fontHeight = fm.getHeight();

        int ybaseline = txtCmp.getY() + fm.getAscent();
        int yend = ybaseline + txtCmp.getHeight();

        int rows = 1;

        while (ybaseline < yend) {
            ybaseline += fontHeight;
            rows++;
        }

        return rows;
    }
}

Related Tutorials