指定された JTextPane 位置の行番号を返すメソッド?
-
01-07-2019 - |
質問
折り返しを有効にした JTextPane 内の特定のテキスト位置の行番号を計算するメソッドを探しています。
例:
これは非常に非常に非常に非常に非常に非常に非常に非常に非常に非常に非常に長い行です。
これもまた非常に非常に非常に非常に非常に非常に非常に非常に非常に非常に非常に長い行です。|
カーソルは 2 行目ではなく 4 行目にあります。
誰かがメソッドの実装を提供してもらえますか:
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さまざまなスタイルでフォーマットされたテキスト断片を処理する代替手段
これを試すことができます:
public int getLineNumberAt(JTextPane pane, int pos) {
return pane.getDocument().getDefaultRootElement().getElementIndex(pos);
}
行番号は常に 0 から始まることに注意してください。
所属していません StackOverflow