Search code examples
javagwt

Where to place images in gwt?


I'm trying to load a simple image in GWT. But it is never found.

    import com.google.gwt.user.client.ui.Image;

    public class ImageTest implements EntryPoint {
        Image image = new Image("test.png");
    }

Result:

[WARN] 404 - GET /test.png (127.0.0.1) 1394 bytes
   Request headers
      Host: 127.0.0.1:8888
      User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0
      Accept: image/png,image/*;q=0.8,*/*;q=0.5
      Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
      Accept-Encoding: gzip, deflate
      Connection: keep-alive
      Referer: http://127.0.0.1:8888/ImageTest.html?gwt.codesvr=127.0.0.1:9997
   Response headers
      Content-Type: text/html; charset=iso-8859-1
      Content-Length: 1394

test.png is placed in the same dir as the ImageTest class. Also I tried putting it under src/main/resources. Same error.

Where does an image have to be located?


Solution

  • You need to put them in your webapp directory (Specified as WAR Directory in GWT settings, near your index.html file).

    Otherwise, you need to specify the relative path like resources/images/yourimg.png for src/main/webapp/resources/images/yourimage.png.

    An alternative would be using Client Bundle:

    public interface AppBundle extends ClientBundle {
    
        @Source("image.png")
        ImageResource myImage();
    
        AppBundle INSTANCE = GWT.create(AppBundle.class);
    
    }
    

    And then in your code:

    AppBundle.INSTANCE.myImage();
    

    In this case your image should be placed in the same package as your AppBundle class.