1

我正在创建一个聊天应用程序,我想将字符串附加到 JEditorPane,所以我使用 JEditorPane.getDocument.insert() 方法来执行此操作:

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

但现在我也想显示图像。我已将内容类型设置为 HTML,并使用它:

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

但是,如果我使用 insert(),我不会在 JEditorPane 上获得图像,但是当我使用 setText() 时会显示图像。请帮忙!!我想做这两件事!

我认为的一种方法可能是使用 getText 获取以前的字符串并将新字符串附加到该字符串,然后使用 setText() 设置整个字符串,但有更好的解决方案吗?

4

1 回答 1

4

使用该setText()方法,它正在为您格式化为 HTML。使用insertString,您的标记将转换为文本。查看文档的源 HTML,您会看到<img src=imagepath>将是<img src=imagepath> .

您需要使用 HTMLDocument 类正确插入图像:

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


    }

}
于 2013-03-09T14:55:20.340 回答