Is there something similar to JTextArea's LineOfOffset(int i) in JTextPane ?

Sandip Chitale

The problem with the question is that the JTextPane (when it has the StyledDocument content) is not organized by line numbers. It's structure is based in sections, paragraphs and runs. The paragraph internally maps to AbstractDocument.BranchElement. Thus the only right way to ask would be what is the index of a branch element at a given offset. That is easy to answer using a combination of following APIs -

public Element javax.swing.text.StyledDocument.getParagraphElement(int pos)
  • Gets the element that represents the paragraph that encloses the given offset within the document.


public Element javax.swing.text.Document.getDefaultRootElement()
public int javax.swing.text.Element.getElementIndex(int offset)
  • Gets the child element index closest to the given offset. The offset is specified relative to the begining of the document.

Returns the root element that views should be based upon, unless some other mechanism for assigning views to element structures is provided.