Question

Je cherche une méthode qui calcule le numéro de ligne d'une position de texte donnée dans un JTextPane avec le retour à la ligne activé.

Exemple:

  

Cette ligne est très très très très très très très très très très très très très très très très très très très très très très très très très longue.
  C’est une autre ligne très très très très très très très très très très très très très très très très très très très très très très très très très longue. |

Le curseur est sur la ligne numéro quatre, pas deux.

Quelqu'un peut-il me fournir la mise en oeuvre de la méthode:

int getLineNumber(JTextPane pane, int pos)
{
     return ???
}
Était-ce utile?

La solution

Essayez ceci

 /**
   * 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;
  }

Autres conseils

http://java-sl.com/tip_row_column.html Une alternative qui fonctionne avec des fragments de texte formatés avec des styles différents

vous pouvez essayer ceci:

public int getLineNumberAt(JTextPane pane, int pos) {
    return pane.getDocument().getDefaultRootElement().getElementIndex(pos);
}

N'oubliez pas que les numéros de ligne commencent toujours à 0.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top