2
我无法让JEditorPane将HTML img标记呈现为图像。所有显示的都是一个占位符图形。以下是我的代码。提前致谢。Java JEditorPane不显示图像
我看到:
我的代码:
import java.awt.*;
import java.io.File;
import java.net.URL;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.text.html.HTMLEditorKit;
public class test
{
private static Hashtable image_cache;
public static void main(String[] args)
{
image_cache = new Hashtable();
URL img_url = null;
try
{
img_url = new File("C:/img/mypic.png").toURI().toURL();
Image img = Toolkit.getDefaultToolkit().createImage (img_url);
image_cache.put(img_url.toURI(), img);
}
catch (Exception e)
{
e.printStackTrace();
}
String html = "<html>" +
"<body>"+
"<img src=\"" + img_url.toString() + "\">" +
"</body>" +
"</html>";
JEditorPane swingbox = new JEditorPane();
swingbox.setEditorKit(new HTMLEditorKit());
swingbox.setContentType("text/html");
swingbox.setText(html);
swingbox.getDocument().putProperty("imageCache", image_cache);
JFrame frame=new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(swingbox);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
谢谢!所以这个工作。 – SoupMonster 2014-12-27 18:15:22
我很惊讶,实际的解决方案更简单。您可以使用我提供的Custom ImageCache,但实际问题很愚蠢。它应该是image_cache.put(img_url,img)而不是image_cache.put(img_url.toURI(),img);; – ZakiMak 2014-12-27 19:18:12