在.jar文件中访问.png图像并使用它 [英] Access .png image in .jar file and use it
问题描述
我有这段代码,但我不知道怎么加载图片stone.png所以我可以使用它。
I have this code but I don't know how to load in the image stone.png so I can use it.
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,这是我第一次尝试这个,所以请不要叫我一个菜鸟。 ;)
I want to display stone.png on the JLabel or JFrame, this is my first time trying this so please don't call me a noob. ;)
推荐答案
存储在Jar文件中的图像(或任何内容)无法像一样访问文件
,而你需要使用 Class#getResource
这将返回一个 URL
哪个可以API的许多部分都可以使用它来加载这些资源。
Images (or anything) stored within a Jar file can't be access like a File
, instead you need to use Class#getResource
which will return a URL
which can be used by many parts of the API to load these resources.
API的一部分不接受 URL
,您可以使用 Class#getResourcesAsStream
,而不是返回 InputStream
。
Where a part of the API doesn't accept a URL
, you can use Class#getResourcesAsStream
which returns an InputStream
instead.
类似......
img = ImageIO.read(MainGame.class.getResource("stone.png"));
这假设 stone.png
是jar文件的默认/顶级目录,如果它在子目录中,则需要指定jar文件根目录的完整路径
This assumes the stone.png
is the default/top level directory of the jar file, if it's within a subdirectory, you will need to specify the full path from the root of the jar file
这篇关于在.jar文件中访问.png图像并使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!