user660231
user660231

Reputation: 21

Problem converting Java applet to Jar. Maybe Image loading problem

I'm writing an applet in eclipse and under the eclipse environment it works well.

while creating a jar file from this project, the problems start.

After testing the jar with several options, I think the problem is with loading an image from a web page.

Any Other features from the applet seems to work ok in the jar.

The code of loading image in my project looks like that:

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);

But the jar can not load the imgae and it doesn't disply it in while running and the applet is stuck because of that. (unlike in the eclipse, which loads the image and shows it)

What could be the problem?

A second problem is that from the applet in the eclipse the loading take few seconds. Is there a way to speed things up?

Thanks for any help,

Upvotes: 2

Views: 780

Answers (1)

Rogach
Rogach

Reputation: 27200

I have no idea how this could be working in Eclipse.

The problem is that getDocumentBase() returns location of a page, in which the applet is embedded (e.g. http://some.site.com/index.html), and you are trying to load a picture from that location. Obviously, there is no picture, just an html (or php) file, and the loading fails.

If your goal is to load an image from inside the jar, try:

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

where "/images/tree.png" is path to image file in your source tree.

EDIT: If you need just to load an image from URL, you can use:

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!");
}

This method is a bit better than Applet.getImage(new URL(...)) - I had some problems when loading many images.

Upvotes: 1

Related Questions