【问题标题】:Access .png image in .jar file and use it访问 .jar 文件中的 .png 图像并使用它
【发布时间】:2015-01-01 07:26:31
【问题描述】:

我有这个代码,但我不知道如何加载图像stone.png,所以我可以使用它。

package mine.mine.mine;

import javax.imageio.ImageIO;
import javax.swing.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class MainGame {
    private static void showGUI()
    {   JFrame frame = new JFrame("Mine Mine Mine");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel emptyLabel = new JLabel("");
    emptyLabel.setPreferredSize(new Dimension(496, 496));
    frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    BufferedImage img = null, diamond = null, emerald = null, gold = null, lapis = null, iron = null, redstone = null, coal = null; //Ignore these.
    try {
        img = ImageIO.read(new File("stone.png")); //Main problem is here. Used debug method on line 27.
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "ERROR: The game has corrupted/missing files. Please redownload the game.", "Mine Mine Mine", JOptionPane.ERROR_MESSAGE);
        JOptionPane.showMessageDialog(null, e.getStackTrace());
    }



}
    public static void main(String args[]){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showGUI();
            }
        });
    }


}

我想在 JLabel 或 JFrame 上显示 stone.png,这是我第一次尝试,所以请不要称我为菜鸟。 ;)

【问题讨论】:

    标签: java image


    【解决方案1】:

    无法像File 那样访问存储在 Jar 文件中的图像(或任何内容),而是需要使用 Class#getResource,它会返回一个 URL,API 的许多部分都可以使用它来加载这些资源。

    如果 API 的一部分不接受 URL,您可以使用返回 InputStreamClass#getResourcesAsStream

    类似...

    img = ImageIO.read(MainGame.class.getResource("stone.png"));
    

    这假定stone.png 是 jar 文件的默认/顶级目录,如果它在子目录中,则需要指定 jar 文件根目录的完整路径

    【讨论】:

    • 嘿,谢谢老兄,它成功了:)。你能帮我在 JLabel/JFrame 上显示该图像吗?
    猜你喜欢
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2011-07-07
    • 2016-03-18
    相关资源
    最近更新 更多