10

I tried the following code:

RootPanel root = RootPanel.get("root");
root.clear();
final FlowPanel p = new FlowPanel();
root.add(p);
for (int i=0; i<20; ++i) {
    String url = "/thumb/"+i;
    final Image img = new Image(url);
    img.addLoadHandler(new LoadHandler() {
        @Override
        public void onLoad(LoadEvent event) {
        p.add(img);
    }
});
Image.prefetch(url);

But it does not work for me. Did I missed something?

Anthony
  • 12,407
  • 12
  • 64
  • 88

3 Answers3

7

Image load handler is called only in the case, when image is attached to the DOM. So you have to add image to the DOM outside the loadHandler:

p.add(img);
img.addLoadHandler(new LoadHandler() {
    @Override
    public void onLoad(LoadEvent event) {
        //do some stuff, image is loaded
    }
}
dreak
  • 71
  • 1
  • 2
  • 1
    dreak is right, your code has a logic error and the img is never attached to the DOM. Compare your code with this snippet – LoneWolf Oct 05 '12 at 06:48
1
ImageElement img = DOM.createImg().cast();
img.setSrc("images/myImage.png");
vinnyjames
  • 2,040
  • 18
  • 26
1

What Stan said makes sense.

I think the problem is that the LoadHandler isn't being called for some reason. I've always managed without a LoadHandler, but I usually add an errorHandler as per the JavaDoc demo which is triggered if loading fails. This should work:

final Image img = new Image();

img.addErrorHandler(new ErrorHandler() {
      public void onError(ErrorEvent event) {
        // Handle the error
      }
    });

img.setUrl(url);
p.add(img);

See the example in the GWT Javadoc: http://google-web-toolkit.googlecode.com/svn/javadoc/2.1/com/google/gwt/user/client/ui/Image.html

Joel
  • 724
  • 5
  • 12