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

Java examples for Swing:JTextComponent

Description

Given a line returns the offset number where the line ends 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 ww  . j  ava 2s . c o  m
     * Given a line returns the offset number where the line ends.
     * 
     * @param line Line number
     * @return Offset number
     */
    public static int getWhereLineEnds(JTextComponent txtCmp, int line) {
        return getWhereLineEnds(txtCmp.getDocument(), line);
    }

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

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

Related Tutorials