Strange modelToView problem...

I need to get position of caret in my jTextPane with monospaced font.

I use following code:

...

private FontMetrics fontMetrics=jTextPane.getFontMetrics(font);

privatestaticint fontWidth=fontMetrics.charWidth(' ');

privatestaticint offset;

try

{

offset=jTextPane.modelToView(0).x;

}

catch (BadLocationException badlocationexception){}

jTextPane.getCaret().addChangeListener(this);

...

publicvoid stateChanged(ChangeEvent e)

{

textPosition=jTextPane.getCaretPosition();

Element rootElemrnt=doc.getDefaultRootElement();

lineCount=rootElemrnt.getElementCount();

coordY=rootElemrnt.getElementIndex(textPosition);

try

{

coordX=(jTextPane.modelToView(textPosition).x-offset)/fontWidth;

}

catch(BadLocationException e1){}

statusBar.setText(" Ln "+(coordY+1)+", Col "+(coordX+1));

}

...

Every time when I press Enter in my jTextPane I have BadLocationException. I don't know why?

[1848 byte] By [bhl2002a] at [2007-10-2 4:35:23]
# 1
Use should be using a CaretListener, not a ChangeListener.Check out this posting to find the row/column position of the caret: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=607777
camickra at 2007-7-16 0:07:52 > top of Java-index,Desktop,Core GUI APIs...
# 2
I tried to use CaretListener and I had BadLocationException too.Besides I can't use method 'caretPosition - lineStart + 1' because I use different tab positions in my jTextPane.
bhl2002a at 2007-7-16 0:07:52 > top of Java-index,Desktop,Core GUI APIs...