首页 > 解决方案 > JTextpane 不显示带有 HTMLEditorkit 和 HTMLDocument 的照片(损坏的图标)

问题描述

当我保存文件时,带有 HTMLEditorKit 和 HTMLDocument 的 Jtextpane 不呈现照片并呈现损坏的图标,我发现照片已加载到 HTML 生成的文件中

try {
                    File f =im.file;
                    icon = new ImageIcon(f.getName());

                    int w = 300;
int h =300;
                    MutableAttributeSet attr = new SimpleAttributeSet();
attr.addAttribute(StyleConstants.NameAttribute,
HTML.Tag.IMG);
attr.addAttribute(HTML.Attribute.SRC, f.getAbsolutePath());
attr.addAttribute(HTML.Attribute.HEIGHT,
Integer.toString(h));
attr.addAttribute(HTML.Attribute.WIDTH,
Integer.toString(w));
int p = editor.getCaretPosition();
doc.insertString(p, " ", attr);

                   HTMLDocument docx = (HTMLDocument)editor.getDocument();
                    HTMLEditorKit kit=(HTMLEditorKit)editor.getEditorKit();
         String filename = f.getAbsolutePath();
    String preTag="<PRE>filename is : "+filename+"</PRE>";
    String imageTag="<img src=\""+filename+"\"/>";
    String s ="<html><img src="+filename+"></img></html>";



 // kit.insertHTML(doc, doc.getLength(), s, 0, 0, HTML.Tag.IMG);


         doc.insertString(editor.getCaretPosition(), "\r\n", editor.getInputAttributes());



                }
````[see the broken icon[\]\[1\][1]


  [1]: https://i.stack.imgur.com/memDr.png

标签: javaswing

解决方案


这是使用 ``file.toURI.toURL().toString() 的方法;`````

try {
                    File f =im.file;
                    icon =(ImageIcon) label.getIcon();
             String filename= f.toURI().toString();  
                    int w =icon.getIconWidth();
int h =icon.getIconHeight();

                    MutableAttributeSet attr = new SimpleAttributeSet();
attr.addAttribute(StyleConstants.NameAttribute,HTML.Tag.IMG);
attr.addAttribute(HTML.Attribute.SRC, filename);
attr.addAttribute(HTML.Attribute.HEIGHT,
Integer.toString(h));
attr.addAttribute(HTML.Attribute.WIDTH,
Integer.toString(w));
int p = editor.getCaretPosition();
doc.insertString(p, " ", attr);
 doc.insertString(editor.getCaretPosition(), "\r\n", editor.getCharacterAttributes());







                } catch (Exception ex) {
                    }

        }

推荐阅读