返回给定JTextPane位置的行号的方法?

Mar*_*rie 3 java user-interface swing jtextpane

我正在寻找一种方法来计算JTextPane中给定文本位置的行号,并启用包装.

例:

这非常非常非常非常非常非常非常非常非常非常非常非常非常长.
这是另一个非常非常非常非常非常非常非常非常非常非常非常非常非常长的路线.|

光标位于第四行,而不是两行.

有人可以为我提供该方法的实现:

int getLineNumber(JTextPane pane, int pos)
{
     return ???
}
Run Code Online (Sandbox Code Playgroud)

Sta*_*avL 6

http://java-sl.com/tip_row_column.html 使用不同样式格式化的文本片段的替代方法


Ric*_*ard 5

试试这个

 /**
   * 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;
  }
Run Code Online (Sandbox Code Playgroud)

  • jtextpane类能够支持可变字体大小,此方法将失败. (2认同)