我试图取出我添加到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

最佳答案

有两件事:


for循环中的变量没有意义。您想一次阅读一行文本,但事先不知道每一行的大小。
getText(...)方法的参数错误


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

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

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

10-07 13:23