在jeditorpane上显示图像(java swing)
我有一个通过这种方式创建的JEditorPane:
JEditorPane pane = new JEditorPane("text/html", "" + my_text_to_show + "" + "");
我将此窗格放在JFrame上。
文字显示正确,但我看不到图片,只有一个方块表示应该有一个图像(即:未找到图片时浏览器显示的“破碎图像”)
您必须提供类型,并获取资源。 就这样。 我测试的例子,但我不确定格式化。 希望能帮助到你:
import java.io.IOException; import javax.swing.JEditorPane; import javax.swing.JFrame; public class Test extends JFrame { public static void main(String[] args) throws Exception { Test.createAndShowGUI(); } private static void createAndShowGUI() throws IOException { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String imgsrc = Test.class.getClassLoader().getSystemResource("a.jpg").toString(); frame.getContentPane().add(new JEditorPane("text/html", "")); frame.pack(); frame.setVisible(true); } }
JEditorPane也使用HTMLDocument.getBase来定位相对URL,因此如果要显示目录中的内容,请确保在html文档上设置基础,以便它相对于基本目录解析URL。
根据图像的实际位置,您可能希望扩展HTMLEditorKit + HTMLFactory + ImageView并提供ImageView的自定义实现,ImageView也负责将属性URL映射到图像URL。
以上都不适合我,但是'imgsrc = new File("passport.jpg").toURL().toExternalForm();'
让我试着让html中的每个图像都有一个前面的’file:’,这样它现在可以读取:
这对我来说很好。
如果要指定图像的相对路径。
假设你的项目文件夹结构如下:
sample_project/images
sample_project/images/loading.gif
sample_project/src
sampler_project/src/package_name
现在图片标签看起来像这样:
""
Yaay!
当我在netbeans工作时,我使用了它,但它工作正常。 如果程序应该在netbeans之外运行,我认为稍加修改,
String imgsrc=""; try { imgsrc = new File("passport.jpg").toURL().toExternalForm(); } catch (MalformedURLException ex) { Logger.getLogger(EntityManager.class.getName()).log(Level.SEVERE, null, ex); } //System.out.println(imgsrc); use this to check html = "
"; //use the html ...
如果从jar运行,则映像文件必须位于同一目录级别,…实际上,映像文件必须与执行条目位于同一目录中。