Ale*_*eng 2 java string algorithm jtextpane listener
问题:我有CaretListener和DocumentListener监听JTextPane.
我需要一个能够在JTextPane中判断哪条线是插入符号的算法,这是一个说明性示例:

结果:第3行

结果:第2行

结果:第4行
如果该算法可以分辨出哪行插入符号是在JTextPane的,它应该是很容易的子无论是在括号中的图片(插入符号是人物之间m的metadata):

-
这就是我将从JTextPane检索到的整个文本分成句子的方式:
String[] lines = textPane.getText().split("\r?\n|\r", -1);
Run Code Online (Sandbox Code Playgroud)
中的句子textPane用\n分隔.
问题是,我如何操纵插入符让我知道它在哪个位置和哪条线?我知道插入符号的点说它在哪个位置,但我不知道它在哪一行.假设我知道插入符号是哪一行,那么我就可以lines[<line number>]从那里操作并操纵字符串.
简而言之:如何使用CaretListener和/或DocumentListener来了解插入符当前所在的行,并检索该行以进行进一步的字符串操作?请帮忙.谢谢.
如果需要进一步澄清,请告诉我.谢谢你的时间.
这是您请求的源代码:
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);
...
}
Run Code Online (Sandbox Code Playgroud)