Marlo Guthrie
Marlo Guthrie

Reputation: 2739

Method that returns the line number for a given JTextPane position?

I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled.

Example:

This a very very very very very very very very very very very very very very very very very very very very very very long line.
This is another very very very very very very very very very very very very very very very very very very very very very very long line.|

The cursor is on line number four, not two.

Can someone provide me with the implementation of the method:

int getLineNumber(JTextPane pane, int pos)
{
     return ???
}

Upvotes: 4

Views: 3775

Answers (3)

Morgan
Morgan

Reputation: 927

you could try this:

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

Keep in mind that line numbers always start at 0.

Upvotes: 1

StanislavL
StanislavL

Reputation: 57381

http://java-sl.com/tip_row_column.html An alternative which works with text fragments formatted with different styles

Upvotes: 6

Richard
Richard

Reputation: 184

Try this

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

Upvotes: 6

Related Questions