javaimageswingjtextpanehtmleditorkit

display HTML image using JTextPane with HTMLEditorKit


For testing purpose I am trying to add a little picture next to each line of document with this code:

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

My problem is that all I see is this, no picture just a frame for it: enter image description here

I might have got the pathing wrong but this should be correct from what I know: enter image description here

This is some more Code of my method:

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();
}
}

Does anyone know why all I can see it the little frame of the picture, did I forget something? Thanks in advance! If you need more Code let me know!


Solution

  • Ok I got it done this way:

        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);
    

    Hope this helps you if you have the same problem :)