9

有没有办法从充满文本的 jtextpane 中“提取”行数?如果有,如果某些行是由于文本换行,它会起作用吗?

4

4 回答 4

14

您可以使用Utilities.getRowStart来确定JTextPane给您结果的行的“开始” lineCount。当换行时,这也将起作用。

int totalCharacters = textPane.getText().length(); 
int lineCount = (totalCharacters == 0) ? 1 : 0;

try {
   int offset = totalCharacters; 
   while (offset > 0) {
      offset = Utilities.getRowStart(textPane, offset) - 1;
      lineCount++;
   }
} catch (BadLocationException e) {
    e.printStackTrace();
}
于 2012-12-10T19:38:24.910 回答
5

如果将“行”定义为 JTextPane 文本中有多少\n个字符,则可以使用:

JTextPane p = yourJTextPane;
System.out.println(p.getText().split("\n").length);
于 2012-12-10T19:18:09.553 回答
0

要跳转到选定的行,我使用了以下代码:

int rowSel = Integer.parseInt(tfGoLine.getText());

        int rowGo = 0;
        int lineCount = 0;
        int totalCharacters = rowSel <= 1 ? 0 : text.getText().length();

        try {
            int last = -1;
            for (int count = 0; count < totalCharacters; count++) {
                int offset = Utilities.getRowStart(text, count);

                if (last != offset) {
                    last = offset;
                    lineCount++;
                    rowGo = offset;

                    if (lineCount == rowSel) {
                        break;
                    }
                }
            }

        } catch (BadLocationException e) {
        }

        text.getCaret().setDot(rowGo);
        text.requestFocus();
于 2015-05-27T17:47:48.150 回答
0
int rowCount =txtPane.getDocument().getDefaultRootElement().getElementCount();
于 2019-05-12T16:25:48.860 回答