java - JEdi​​torPane 的 html 中的插入符号位置

标签 java image swing caret jeditorpane

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 - JEdi​​torPane 的 html 中的插入符号位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8866369/

相关文章:

java - 将 Cursor 转换为通用对象 android

java - Eclipse-Oxygen 无法运行 Arquillian 单元测试

javascript - 定期刷新页面上的图像

jquery - 使用 jquery 的图像大小没有在标签中预先定义然后传递给 CSS

c - 在微 Controller 屏幕上显示图片

java - 如何在 Java 项目中构建我的类

java - 错误消息 "non-static variable this cannot be referenced from a static context"第 18 行

java - 鼠标光标在对象上滚动时不会改变

java - 将 JPanel 转换为 JScrollPane 中的图像

java - 将表上的数据显示到 jfreechart 中