سؤال

أنا أبحث عن طريقة تحسب رقم السطر لموضع نص معين في 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