【问题标题】:display HTML image using JTextPane with HTMLEditorKit使用带有 HTMLEditorKit 的 JTextPane 显示 HTML 图像
【发布时间】:2016-01-30 03:36:40
【问题描述】:

出于测试目的,我尝试使用以下代码在文档的每一行旁边添加一张小图片:

kit.insertHTML(doc, doc.getLength(), "<IMG SRC=file://res/picture.png>", 0, 0, HTML.Tag.IMG);

我的问题是我看到的只是这个,没有图片只是一个框架:

我可能弄错了路径,但据我所知,这应该是正确的:

这是我的方法的更多代码:

public void addText(String text, boolean timestamp) {
long timeMS = System.currentTimeMillis();
Date instant = new Date(timeMS);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String time = sdf.format(instant);

boolean shouldScroll = false;

try {
    HTMLDocument doc = (HTMLDocument) getChat().getDocument();
    HTMLEditorKit kit = (HTMLEditorKit) getChat().getEditorKit();
    JScrollBar vsb = getChatScroller().getVerticalScrollBar();

    BoundedRangeModel model = vsb.getModel();
    if (model.getExtent() + model.getValue() == model.getMaximum())
    shouldScroll = true;
    kit.insertHTML(doc, doc.getLength(), timestamp ? time + ": " + text : text, 0, 0, null);
    kit.insertHTML(doc, doc.getLength(), "<IMG SRC=file://res/picture.png>", 0, 0, HTML.Tag.IMG);
    if (shouldScroll)
    getChat().setCaretPosition(doc.getLength());
} catch (IOException | BadLocationException e) {
    e.printStackTrace();
}
}

有谁知道为什么我只能看到图片的小框架,我是不是忘记了什么?提前致谢!如果您需要更多代码,请告诉我!

【问题讨论】:

    标签: java image swing jtextpane htmleditorkit


    【解决方案1】:

    好的,我是这样搞定的:

        String filename = getClass().getClassLoader().getResource("res/Kappa.png").toString();
        String preTag="<PRE>filename is : "+filename+"</PRE>";
        String imageTag="<img src=\""+filename+"\"/>";
        kit.insertHTML(doc, doc.getLength(), preTag+imageTag, 0, 0, HTML.Tag.IMG);
    

    如果您遇到同样的问题,希望这对您有所帮助:)

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2012-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多