2008-09-19 36 views
3

我正在尋找一種方法,可以計算JTextPane中給定文本位置的行號並啓用換行。返回給定JTextPane位置的行號的方法?

實施例:

這一個非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常長行。
這是另一個非常非常非常非常甚至非常非常非常非常甚至非常非常非常甚|

遊標在第四行,而不是兩行。

有人能給我提供的方法實現:

int getLineNumber(JTextPane pane, int pos) 
{ 
    return ??? 
} 

回答

5

試試這個

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

jtextpane類能夠支持可變字體大小,此方法將在該場景下失敗。 – GlassGhost 2011-03-18 17:09:50

1

你可以試試這個:

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

請記住,行號總是從0開始。

相關問題