java - 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
解决方案
这是使用 ``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) {
}
}
推荐阅读
- c# - 事后修复错误编码的字符串
- reactjs - 如何为高度嵌套的子组件使用 Redux 表单?
- python - Python VLC - 获取位置轮询率解决方法
- java - 无法按下表格单元格中的按钮
- html - 如果不同来源请求相同的资源,浏览器会从缓存中提取吗?
- amazon-web-services - AWS-CDK Lambda 和测试
- javascript - 如何从 Windows 上的节点中的谷歌浏览器获取浏览器历史记录?
- java - JDBC 规范是否定义了如果为具有冲突列名的查询调用 `ResultSet.getObject(String)` 会发生什么?
- solidity - 元掩码错误:事务错误。合约代码中抛出的异常
- jquery - 如何使用 ajax 更新 woocommerce 上的结帐页面而不重新加载/刷新