JEditorPane 的 getCaretPosition 方法给出了 html 控件的纯文本部分的索引。是否有可能将索引获取到 html 文本中?
更具体地说,假设我有一个 html 文本(其中 | 表示插入符号位置)
abcd<img src="1.jpg"/>123|<img src="2.jpg"/>
现在 getCaretPosition 给出 8,而我需要 25 作为结果来读出图像的文件名。
最佳答案
我遇到了大部分相同的问题并使用以下方法解决了它(我使用了 JTextPane
,但对于 JEditorPane
应该是相同的):
public int getCaretPositionHTML(JTextPane pane) {
HTMLDocument document = (HTMLDocument) pane.getDocument();
String text = pane.getText();
String x;
Random RNG = new Random();
while (true) {
x = RNG.nextLong() + "";
if (text.indexOf(x) < 0) break;
}
try {
document.insertString(pane.getCaretPosition(), x, null);
} catch (BadLocationException ex) {
ex.printStackTrace();
return -1;
}
text = pane.getText();
int i = text.indexOf(x);
pane.setText(text.replace(x, ""));
return i;
}
它只是假设您的 JTextPane 不会包含所有可能的 Long
值;)
关于java - JEditorPane 的 html 中的插入符号位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8866369/