Returns the line number of the caret in a text component. - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

Returns the line number of the caret in a text component.

Demo Code


//package com.java2s;

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

public class Main {
    /**/* www . j  a  va2 s. c  om*/
     * Returns the line number of the caret in a text component.
     * 
     * @param txtCmp Text Component
     * @return Line number
     */
    public static int getCaretLine(JTextComponent txtCmp) {
        return getLine(txtCmp.getDocument(), txtCmp.getCaretPosition());
    }

    /**
     * Given an offset, returns the line number of a text component.
     * 
     * @param txtCmp Text Component
     * @param offset Offset position
     * @return Line number starting in 0.
     */
    public static int getLine(JTextComponent txtCmp, int offset) {
        return getLine(txtCmp.getDocument(), offset);
    }

    /**
     * Given an offset, returns the line number in a text component.
     * 
     * @param doc JTextComponent document
     * @param offset Offset position
     * @return Line number starting in 0.
     */
    public static int getLine(Document doc, int offset) {
        Element root = doc.getDefaultRootElement();
        return root.getElementIndex(offset);
    }
}

Related Tutorials