Java JTextComponent getRenderedLineOfChar(JTextComponent comp, int charIdx)

Here you can find the source of getRenderedLineOfChar(JTextComponent comp, int charIdx)

Description

Determines the displayed line on which a given character is rendered on a JTextComponent.

License

Open Source License

Parameter

Parameter Description
comp The text component
charIdx The index of the requested character

Return

The displayed line number of the character

Declaration

public static int getRenderedLineOfChar(JTextComponent comp, int charIdx) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import javax.swing.text.*;

public class Main {
    /**//from   w  ww .j a  v a  2 s  .  co  m
     * Determines the displayed line on which a given character is rendered on a JTextComponent.
     *
     * The displayed line is the line that the character appears on after the string has been line-wrapped to fit the
     * bounds of the text view. This is not necessarily the same as the physical line of the character (i.e., the number
     * of '\n' characters that proceed it).
     *
     * @param comp      The text component
     * @param charIdx   The index of the requested character
     * @return          The displayed line number of the character
     */
    public static int getRenderedLineOfChar(JTextComponent comp, int charIdx) {
        int charCount = 0;
        int lineCount = 0;

        View document = comp.getUI().getRootView(comp).getView(0);

        if (document != null) {

            // Walk each paragraph in document
            for (int paragraphIdx = 0; paragraphIdx < document.getViewCount(); paragraphIdx++) {
                View paragraph = document.getView(paragraphIdx);

                // Walk each line in paragraph
                for (int lineIdx = 0; lineIdx < paragraph.getViewCount(); lineIdx++) {
                    View line = paragraph.getView(lineIdx);

                    // Walk each char in the line
                    charCount += line.getEndOffset() - line.getStartOffset();

                    if (charCount >= charIdx) {
                        return lineCount;
                    }

                    lineCount++;
                }
            }
        }

        return 0;
    }
}

Related

  1. getCurrentTextBlock(JTextComponent textComponent)
  2. getNumberOfLines(final JTextComponent component)
  3. getParagraphElement(JTextComponent c, int offs)
  4. getPositionBelow(JTextComponent c, int offs, int x)
  5. getPreferredScrollableViewportSize(javax.swing.text.JTextComponent t, Dimension ans)
  6. getStoredBackground(JTextComponent comp)
  7. getStoredBackground(JTextComponent comp)
  8. highlighterIsNext(JTextComponent textComponent, boolean forwards, Highlighter.Highlight highlight)
  9. implyDisabled(final JCheckBox checked, final boolean checkedState, final JTextComponent changed)