将Java applet转换为Jar的问题。也许图像加载问题

时间:2011-03-15 09:10:01

标签: java image jar applet

我正在eclipse中编写一个applet,在eclipse环境下它运行良好。

从这个项目创建一个jar文件时,问题就开始了。

使用多个选项测试jar后,我认为问题在于从网页加载图像。

小程序中的任何其他功能似乎都可以在jar中正常工作。

我项目中加载图片的代码如下:

MediaTracker mt = new MediaTracker(this);
String photo = imagePath
URL base = null;
 try { 
 base = getDocumentBase(); 
 } 
 catch (Exception e) {
}
 if(base == null){
      System.out.println("ERROR LOADING IMAGE");
 }
 Image imageBase = getImage(base,photo); 
// Some code that works on the image (not relevant)

   // The rest of the code
    icon.setImage(image);
   imageLabel.setIcon(icon);

但是jar无法加载imgae并且它在运行时不会显示它并且applet因此而被卡住。 (与日食不同,它会加载图像并显示它)

可能是什么问题?

第二个问题是,从日食中的applet加载需要几秒钟。有没有办法加快速度?

感谢您的帮助,

1 个答案:

答案 0 :(得分:1)

我不知道这在Eclipse中是如何工作的。

问题是getDocumentBase()返回页面的位置,其中嵌入了applet(例如http://some.site.com/index.html),并且您正在尝试从该位置加载图片。显然,没有图片,只有一个html(或php)文件,加载失败。

如果你的目标是从jar中加载图像,请尝试:

Image img = null;
try {
    img = ImageIO.read(getClass().getResource("/images/tree.png"));
} catch (IOException ex) {
    System.err.println("Picture loading failed!");
}

其中“/images/tree.png”是源树中图像文件的路径。

编辑:如果您只需要从网址加载图片,可以使用:

Image img = null;
try {
    img = ImageIO.read(new URL("http://some.site.com/images/tree.png"));
} catch (IOException ex) {
    System.err.println("Picture loading failed!");
}

这个方法比Applet.getImage(新的URL(...))好一点 - 加载很多图像时遇到了一些问题。

相关问题