Given an offset, returns the offset where the line ends. - Java 2D Graphics

Java examples for 2D Graphics:Line

Description

Given an offset, returns the offset where the line ends.

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  a va  2  s . c  om
     * Given an offset, returns the offset where the line ends.
     * 
     * @param offset Offset position.
     * @return Offset where the line ends.
     */
    public static int getOffsetEndLine(JTextComponent txtCmp, int offset) {
        return getOffsetEndLine(txtCmp.getDocument(), offset);
    }

    /**
     * Given an offset, returns the offset where the line ends.
     * 
     * @param doc JTextComponent document
     * @param offset Offset position.
     * @return Offset where the line ends.
     */
    public static int getOffsetEndLine(Document doc, int offset) {
        int line = getLine(doc, offset);
        return getWhereLineEnds(doc, line);
    }

    /**
     * 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);
    }

    /**
     * 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