在 jeditorpane (java swing) 上显示图像
我通过这种方式创建了一个 JEditorPane:
JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>");
我将此窗格放在 JFrame 上。
文本显示正确,但我看不到图片,只有一个方块表示应该有图像(即:当未找到图片时浏览器显示“损坏的图像”)
I have a JEditorPane created by this way:
JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>");
I put this pane on a JFrame.
Text is shown correctly, but I can't see the picture, there is only a square indicating that there should be an image (i.e.: "broken image" shown by browsers when picture has not been found)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须提供类型并获取资源。 就这样。 我测试过的示例,但我不确定格式。 希望能帮助到你:
You have to provide type, and get the resource. That's all. My tested example, but I'm not sure about formating. Hope it helps:
JEditorPane 也使用 HTMLDocument.getBase 来定位相对 url,因此,如果您要显示目录中的内容,请确保在 html 文档上设置基址,以便它解析相对于基目录的 url。
根据图像的实际位置,您可能需要扩展 HTMLEditorKit+HTMLFactory+ImageView 并提供 ImageView 的自定义实现,它也负责将属性 URL 映射到图像 URL。
The JEditorPane is using HTMLDocument.getBase to locate relative urls as well, so if you are displaying content from a directory, make sure to set the base on the html document so it resolves urls relative to the base directory.
Depending on where that image actually is, you might want to extend HTMLEditorKit+HTMLFactory+ImageView and provide a custom implementation of ImageView, which is responsible for mapping the attribute URL to the image URL, too.
以上都不适合我,但是
'imgsrc = new File("passport.jpg").toURL().toExternalForm();'
让我尝试让 html 中的每个图像具有前面的“文件:”现在显示为:这对我来说效果很好。
None of the above worked for me, however
'imgsrc = new File("passport.jpg").toURL().toExternalForm();'
let me to try and have each image in the html have a preceding 'file:' so that it now reads:And that works fine for me.
如果要指定图像的相对路径。
假设您的项目文件夹结构如下:
sample_project/images
sample_project/images/loading.gif
sample_project/src
sampler_project/src/package_name
现在图像标签将如下所示:
""
耶!
If you want to specify relative path to the image.
Let's say your project folder structure is as following:
sample_project/images
sample_project/images/loading.gif
sample_project/src
sampler_project/src/package_name
Now the image tag would look like this:
"<img src='file:images/loading.gif' width='100' height='100'>"
Yaay!
我在 netbeans 工作时使用过这个,但它确实有效。 我认为如果程序应该在 netbeans 之外运行,则需要进行一些修改,
如果从 jar 运行,则图像文件必须位于同一目录级别,...
事实上,图像文件必须与执行条目位于同一目录中。
I used this when I was working in netbeans, it worked though. I think a little modification if the program should run outside of netbeans,
if you run from the jar, the image file has to be on the same directory level, ...
in fact, the image file has to be on the same directory as your execution entry.