【问题标题】:Java reference internal image file [duplicate]Java参考内部图像文件[重复]
【发布时间】:2014-02-12 19:58:20
【问题描述】:

我正在尝试将图像设置为 JLabel,在我的项目中我有一个文件夹“images”,其中是 logo.png

我正在使用下面的代码来获取它

BufferedImage myPicture = null;

    try {
        myPicture = ImageIO.read(new File("images/logo.png"));
    } catch (IOException e1) {

        e1.printStackTrace();
    }

    JLabel headerImage = new JLabel(new ImageIcon(myPicture));

这个工作文件在 eclipse 中,但是在可运行的 jar 之外不会触发,除非它与包含徽标文件的文件夹 images 位于同一目录中。

所以我的问题是如何将图像打包到 .jar 文件中并让这段代码引用它?

【问题讨论】:

    标签: java image swing embedded-resource


    【解决方案1】:

    您需要从类路径而不是从本地磁盘文件系统中获取它。

    假设 images 实际上是一个包,并且这个包与当前类在同一个 JAR 中,那么这样做:

    BufferedImage myPicture = null;
    try {
        myPicture = ImageIO.read(getClass().getResource("/images/Report.png"));
    } catch (IOException e1) {
    
        e1.printStackTrace();
    }
    
    JLabel headerImage = new JLabel(new ImageIcon(myPicture));
    

    【讨论】:

    • 谢谢,还指出需要的文件结构,我不知道
    【解决方案2】:

    试试这个对我来说很好用

       ImageIO.read(getClass().getResource("images/logo.png"));
    

    【讨论】:

      【解决方案3】:

      您可以使用以下方式从类路径中读取图像文件:

      this.getClass().getResourceAsStream("logo.png");

      查看this blog post 获取完整示例。

      【讨论】:

        猜你喜欢
        • 2020-11-02
        • 1970-01-01
        • 1970-01-01
        • 2021-05-28
        • 1970-01-01
        • 2012-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多