Given a line returns the offset number where the line starts in JTextComponent. - Java Swing

Java examples for Swing:JTextComponent

Description

Given a line returns the offset number where the line starts in JTextComponent.

Demo Code


//package com.java2s;

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

public class Main {
    /**/* w  w  w  . j  av  a 2 s.  c o m*/
     * Given a line returns the offset number where the line starts.
     * 
     * @param line Line number
     * @return Offset number
     */
    public static int getWhereLineStarts(JTextComponent txtCmp, int line) {
        return getWhereLineStarts(txtCmp.getDocument(), line);
    }

    /**
     * Given a line returns the offset number where the line starts.
     * 
     * @param doc JTextComponent document
     * @param line Line number
     * @return Offset number
     */
    public static int getWhereLineStarts(Document doc, int line) {
        Element el = doc.getDefaultRootElement().getElement(line);
        if (el != null)
            return el.getStartOffset();

        return doc.getStartPosition().getOffset();
    }
}

Related Tutorials