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

半世苍凉 提交于 2019-12-05 23:18:18

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!