Inserting images in JEditorPane using pane.getDocument.insert()

梦想与她 提交于 2019-12-23 02:42:40

问题


I am creating a chat application and I want to append strings into JEditorPane, so I am using JEditorPane.getDocument.insert() method to do this:

clientListDoc.insertString(clientListDoc.getLength(),image+"-"+name[0]+"\n", null);

But now I also want to display images. I have set the content type to HTML and I use this:

String temp=ClassLoader.getSystemResource("images/away.png").toString();
image="<img src='"+temp+"'></img>";

But I don't get images on JEditorPane if I use insert() but when I use setText() images are displayed. Please help!! I want to do both these things!

One approach I though could be to use getText to get the previous strings and append the new string to this string and then use setText() to set the entire string but is there a better solution?


回答1:


With the setText() method, it is being formated to HTML for you. With insertString, your markups are converted to text. Look at the source HTML of your document, you'll see that < img src=imagepath > will be & lt;img src=imagepath & gt;.

You'll need to use HTMLDocument class to insert your image properly:

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

class Test {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JEditorPane edPane = new JEditorPane(); 

        try {

            edPane.setContentType("text/html");

            System.out.println(edPane.getText());

            HTMLEditorKit hek = new HTMLEditorKit();

            edPane.setEditorKit(hek);

            HTMLDocument doc = (HTMLDocument) edPane.getDocument();

            doc.insertString(0, "Test testing", null);

            Element[] roots = doc.getRootElements();
            Element body = null;
            for( int i = 0; i < roots[0].getElementCount(); i++ ) {
                Element element = roots[0].getElement( i );
                if( element.getAttributes().getAttribute( StyleConstants.NameAttribute ) == HTML.Tag.BODY ) {
                    body = element;
                    break;
                }
            }

            doc.insertAfterEnd(body,"<img src="+ClassLoader.getSystemResource("thumbnail.png").toString()+">");
            System.out.println(edPane.getText());
        } catch(BadLocationException e) {
        } catch (java.io.IOException e) {}


        frame.add(edPane);

        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);


    }

}


来源:https://stackoverflow.com/questions/15311188/inserting-images-in-jeditorpane-using-pane-getdocument-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!