BadLocationException when using Utilities.getRowStart On hit of Enter key

廉价感情. 提交于 2020-01-06 07:45:09

问题


I am using Utilities.getRowStart to find out the number of lines in a JTextPane. But it gives the BadLocationException when I hit the enter key:

javax.swing.text.BadLocationException: Position not represented by view

Any idea?

int offset = pane.getText().length();

while(offset > 0) {

    try {

    offset = Utilities.getRowStart(pane, offset) - 1;

        } catch (BadLocationException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();

    }
    lineCount++;
}

回答1:


int offset = pane.getText().length();

Just a guess that you are working on Windows. That code will return a string containing "\r\n" for every newline character. The Document only uses "\n" so your offset will be greater than the length of the document. Use:

int offset = pane.getDocument().getLength();


来源:https://stackoverflow.com/questions/15719770/badlocationexception-when-using-utilities-getrowstart-on-hit-of-enter-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!