Swing DefaultStyledDocument遍历

Swing DefaultStyledDocument traversal

我正在尝试提取已添加到 DefaultStyledDocument 的四个段落。但它的行为并不像我预期的那样。

我做错了什么?我已经在此处添加了完整的代码 - 正如所要求的那样。

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Element;

 public class MainFrame extends JFrame {

 JTextPane jTextPane = new JTextPane();

public static void main(String[] args) {
    new MainFrame().init();
    try {
        Thread.sleep(95000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void init() {
    JFrame frame = new JFrame();
    frame.setSize(1000, 800);
    frame.setVisible(true);

    jTextPane.setSize(995, 795);
    frame.add(jTextPane);

    DefaultStyledDocument document = new DefaultStyledDocument();

    try {
        document.insertString(document.getLength(), "DDDD\n", null);
        document.insertString(document.getLength(), "CCCC\n", null);
        document.insertString(document.getLength(), "BBBB\n", null);
        document.insertString(document.getLength(), "AAAA\n", null);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }

    document.dump(System.out);
    jTextPane.setDocument(document);

    for (int x = 0; x < 20; x += 5) {
        Element paraGE = document.getParagraphElement(x);
        int startOff = paraGE.getStartOffset();
        int endOff = paraGE.getEndOffset();
        String s = null;
        try {
            s = document.getText(startOff, endOff);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        System.out.println(s);
    }
}
}

javax.swing.text.BadLocationException: Invalid location
at javax.swing.text.GapContent.getChars(GapContent.java:189)
at javax.swing.text.GapContent.getString(GapContent.java:167)
at javax.swing.text.AbstractDocument.getText(AbstractDocument.java:770)
at blah.MainFrame.init(MainFrame.java:60)
at blah.MainFrame.main(MainFrame.java:14)
javax.swing.text.BadLocationException: Invalid location
at javax.swing.text.GapContent.getChars(GapContent.java:189)
at javax.swing.text.GapContent.getString(GapContent.java:167)
at javax.swing.text.AbstractDocument.getText(AbstractDocument.java:770)
at blah.MainFrame.init(MainFrame.java:60)
at blah.MainFrame.main(MainFrame.java:14)
null
null

几件事:

  1. for 循环中的变量没有意义。您想一次阅读一行文本,并且事先不知道每行的大小。

  2. getText(...)方法的参数错误

您可以使用 Document 中的 Element class 来获取文本行。

未经测试的代码可能类似于:

Element root = textPane.getDocument().getDefaultRootElement();
int lines = root.getElementCount();

for (int i = 0; i < lines; i++)
{
    Element line = root.getElement( i ); 
    int start = line.getStartOffset();
    int end = line.getEndOffset();
    String text = document.getText(start, end - start);
    System.out.println(text);
}