当我将程序作为 Java 应用程序
运行时,一切正常。但是,当我将程序作为 Java Applet
运行时,图像不会加载,并且我得到以下堆栈跟踪:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at com.asgoodasthis.squares.Tile.<init>(Tile.java:42)
at com.asgoodasthis.squares.Component.start(Component.java:80)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
我的项目目录中有一个名为 res 的目录,我正在加载图像,如下所示:
public static BufferedImage tileset_terrain;
public loadImage() {
try {
//loading our images
tileset_terrain = ImageIO.read(new File("res/tileset_terrain.png"));
} catch(IOException e1) {
e1.printStackTrace();
}
}
那么,当我将程序作为 applet
运行时,如何加载图像呢?我正在使用 Eclipse IDE。
最佳答案
很可能无法从当前上下文访问图像,请记住,小程序通常在非常严格的安全沙箱中运行,这会阻止它们访问本地/客户端文件系统上的文件。
您需要从加载小程序的服务器加载图像(使用 getDocument/CodeBase
或相对 URL),或者根据您的示例,例如嵌入资源
tileset_terrain = ImageIO.read(getClass().getResource("/res/tileset_terrain.png"));
这假设图像包含在 /res
目录下的 Jar 文件中。
如果图像驻留在加载小程序的服务器上,您也可以使用
try {
URL url = new URL(getCodeBase(), "res/tileset_terrain.png");
img = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
看看Reading/Loading images和What Applets Can and Cannot Do了解更多详情。
关于java - 在Java Applet中加载并显示本地镜像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969217/