如何从jtextpane获取行数

时间:2012-12-10 19:13:39

标签: java swing jtextpane linewrap

有没有办法从填充文本jtextpane中“提取”行数? 如果有的话,如果某些行是由文本换行引起的吗?

4 个答案:

答案 0 :(得分:13)

您可以使用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();
}

答案 1 :(得分:5)

如果你定义一个"行"如JTextPane文本中有多少\n个字符,那么您可以使用:

JTextPane p = yourJTextPane;
System.out.println(p.getText().split("\n").length);

答案 2 :(得分: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();

答案 3 :(得分:0)

int rowCount =txtPane.getDocument().getDefaultRootElement().getElementCount();