A method that returns the line number for a given JTextPane position?

I am looking for a method that calculates the line number of a given text position in a JTextPane with wrapper enabled.

Example:

It is very very very very very very very very very very very very very very very very very very very very long. It is still very very very very very very very very very very very very very very very long. |

The cursor is on line number four, not two.

Can someone provide me with an implementation of the method:

int getLineNumber(JTextPane pane, int pos)
{
     return ???
}
+3
source share
3 answers

try it

 /**
   * Return an int containing the wrapped line index at the given position
   * @param component JTextPane
   * @param int pos
   * @return int
   */
  public int getLineNumber(JTextPane component, int pos) 
  {
    int posLine;
    int y = 0;

    try
    {
      Rectangle caretCoords = component.modelToView(pos);
      y = (int) caretCoords.getY();
    }
    catch (BadLocationException ex)
    {
    }

    int lineHeight = component.getFontMetrics(component.getFont()).getHeight();
    posLine = (y / lineHeight) + 1;
    return posLine;
  }
+5
source

you can try the following:

public int getLineNumberAt(JTextPane pane, int pos) {
    return pane.getDocument().getDefaultRootElement().getElementIndex(pos);
}

Keep in mind that line numbers always begin with 0.

+2
source

Source: https://habr.com/ru/post/1697207/


All Articles