Here you can find the source of getRenderedLineOfChar(JTextComponent comp, int charIdx)
Parameter | Description |
---|---|
comp | The text component |
charIdx | The index of the requested character |
public static int getRenderedLineOfChar(JTextComponent comp, int charIdx)
//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; } }