时出现BadLocationException按下Enter键时

时出现BadLocationException按下Enter键时

本文介绍了使用Utilities.getRowStart时出现BadLocationException按下Enter键时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Utilities.getRowStart找出JTextPane中的行数.但是当我按下Enter键时,它会给出BadLocationException:

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:

有什么主意吗?

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++;
}

推荐答案

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

猜测您正在使用Windows.该代码将为每个换行符返回一个包含"\ r \ n"的字符串.该文档仅使用"\ n",因此您的偏移量将大于该文档的长度.使用:

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();

这篇关于使用Utilities.getRowStart时出现BadLocationException按下Enter键时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 08:07