문제

줄 바꿈이 활성화된 JTextPane에서 지정된 텍스트 위치의 줄 번호를 계산하는 메서드를 찾고 있습니다.

예:

이것은 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 긴 줄입니다.
이것은 또 다른 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 매우 긴 줄입니다.|

커서는 두 번째 줄이 아닌 네 번째 줄에 있습니다.

누군가 나에게 메소드 구현을 제공할 수 있습니까?

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부터 시작한다는 점을 명심하세요.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top