返回给定JTextPane位置的行号的方法?
时间:2020-03-06 14:26:08 来源:igfitidea点击:
我正在寻找一种方法,该方法在启用换行的情况下计算JTextPane中给定文本位置的行号。
例子:
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.|
光标位于第四行,而不是第二行。
有人可以为我提供该方法的实现:
int getLineNumber(JTextPane pane, int pos) { return ??? }
解决方案
试试这个
/** * 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
一种替代方法,适用于以不同样式设置格式的文本片段