【发布时间】:2012-03-21 05:01:36
【问题描述】:
我的应用程序在 JEditorPane 中显示 RSS 条目。它的效果还不错,但是我最近在显示 gif 时遇到了一个严重的问题。这是一个小测试用例:
public class JEditorPaneTest
{
public static void main(String[] args)
{
JFrame dialog = new JFrame("JEditorPane test");
dialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = dialog.getContentPane();
c.setLayout(new BorderLayout());
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setText("<html><body><img src=\"http://feeds.feedburner.com/~ff/MacRumors-All?d=yIl2AUoC8zA\"></body></html>");
c.add(new JScrollPane(editorPane), BorderLayout.CENTER);
dialog.pack();
dialog.setVisible(true);
}
}
非动画 gif 闪烁,在 Mac OS X 上 CPU 使用率高达 300%(四核计算机)或在 Windows 7 上高达 50%。这个问题更加严重,因为在处理编辑器窗格后,CPU 使用率还是那么高。
查看一些分析,看起来 50% 的 cpu 使用时间在 Event dispatcher 线程中,另外 50% 在 sun.awt.image.ImageFetcher.run() 中。
另一个有趣的事实是,在 JLabel 中嵌入 html 时也会发生这种情况。
(编辑:2012 年 3 月 9 日)另一个有趣的事实是,如果文件首先在本地下载(并通过 file://... 访问),或者甚至是资源,则不会修复任何问题。但是如果图像显示在 JLabel 中的 ImageIcon 中,则没有闪烁和高 CPU 使用率。不知何故,我确实需要在 JEditorPane 中使用 HTML 文档来呈现一些基本的 HTML 格式。
我正在寻找一种通用的解决方案来避免审查来自 feedburner.com 的图像,并且来自 feedburner.com 的这些 gif 是我发现的唯一一个,但我想防止所有其他可能表现的图像出现错误同样的方式。
非常感谢。
【问题讨论】:
-
我的猜测是,最好使用 HttpURLConnection 类将图像读入代码,然后在 editorPane 中显示图像。
-
感谢吉尔伯特的建议,但实际上使用本地保存的文件并使用 并不能解决问题。
-
我想我不清楚。将图像读入您的 Java 程序,得到一个 BufferedImage 或 Image 作为结果。然后转换为 ImageIcon 以显示在您的 editorPane 中。
-
有趣。您是否建议我应该覆盖 HTMLEditorKit 这样做?我在 JEditorPane 中找不到任何将图像直接注入文档的方法。
-
我想到了一个 JLabel。看看我的回答是否更有意义。
标签: java performance swing gif jeditorpane