2

问题:我有 CaretListener 和 DocumentListener 在 JTextPane 上监听。

我需要一个能够判断 JTextPane 中插入符号所在的行的算法,这是一个说明性示例:

替代文字

结果:第三行

替代文字

结果:第二行

替代文字

结果:第四行

并且如果算法可以判断插入符号在 JTextPane 中的哪一行,那么将括号之间的任何内容作为图片的子串应该相当容易(插入符号在字符mmetadata):

替代文字

--

这就是我将从 JTextPane 检索到的整个文本分成句子的方式:

String[] lines = textPane.getText().split("\r?\n|\r", -1);

中的句子textPane用 \n 分隔。

问题是,我怎样才能操纵插入符号让我知道它在哪个位置和哪一行?我知道插入符号的点表示它在哪个位置,但我不知道它在哪一行。假设我知道插入符号是哪一行,那么我可以lines[<line number>]从那里做和操作字符串。

简而言之:我如何使用CaretListener 和/或 DocumentListener来知道插入符当前位于哪一行,并检索该行以进行进一步的字符串操作?请帮忙。谢谢。

如果需要进一步澄清,请告诉我。谢谢你的时间。

4

3 回答 3

9

这是您要求的源代码:

static int getLineOfOffset(JTextComponent comp, int offset) throws BadLocationException {
    Document doc = comp.getDocument();
    if (offset < 0) {
        throw new BadLocationException("Can't translate offset to line", -1);
    } else if (offset > doc.getLength()) {
        throw new BadLocationException("Can't translate offset to line", doc.getLength() + 1);
    } else {
        Element map = doc.getDefaultRootElement();
        return map.getElementIndex(offset);
    }
}

static int getLineStartOffset(JTextComponent comp, int line) throws BadLocationException {
    Element map = comp.getDocument().getDefaultRootElement();
    if (line < 0) {
        throw new BadLocationException("Negative line", -1);
    } else if (line >= map.getElementCount()) {
        throw new BadLocationException("No such line", comp.getDocument().getLength() + 1);
    } else {
        Element lineElem = map.getElement(line);
        return lineElem.getStartOffset();
    }
}

...

public void caretUpdate(CaretEvent e) {
    int dot = e.getDot();
    int line = getLineOfOffset(textComponent, dot);
    int positionInLine = dot - getLineStartOffset(textComponent, line);
    ...
}
于 2010-05-01T13:31:19.113 回答
2

在带有 JTextPane.getStyledDocument的StyledDocument中使用段落的概念。

通过光标的位置,您可以通过 StyledDocument.getParagraph(pos) 了解当前段落。然后你迭代从 StyledDocument.getRootElements 和 children 中抛出段落,以搜索当前段落的数量,因此当前行的数量。

对不起我的英语不好。

于 2010-05-01T13:30:04.310 回答
1

这就是我将从 JTextPane 检索到的整个文本分成句子的方式:

您的解决方案效率不高。

首先,无论使用什么操作系统,文档中都只会存储一个“\n”。所以你可以简化正则表达式。

但是,不需要使用正则表达式来解析整个 Document,因为您只关心 Document 中的 1 行。现在您了解了 Element 接口,您可以使代码更高效。

a) 获取前面演示的行
b) 现在您可以从根元素获取该行表示的元素
c) 现在您可以使用开始/结束偏移量和 getText(...) 方法仅获取文本对于该特定行。

于 2010-05-01T16:01:28.213 回答