2011-03-10 59 views
1

使用GWT我正在用ClickHandler顯示圖片縮略圖,然後在居中的PopupPanel中顯示完整圖片(可能爲幾MB)。爲了讓它居中,必須在顯示彈出窗口之前加載圖像,否則圖像的左上角放置在屏幕中間(圖像認爲它是1px大)。這是我使用這樣做代碼:在居中的PopupPanel中顯示GWT圖片onLoad

private void showImagePopup() { 
     final PopupPanel popupImage = new PopupPanel(); 
     popupImage.setAutoHideEnabled(true); 
     popupImage.setStyleName("popupImage"); /* Make image fill 90% of screen */ 

     final Image image = new Image(); 
     image.addLoadHandler(new LoadHandler() { 
      @Override 
      public void onLoad(LoadEvent event) { 
       popupImage.add(image); 
       popupImage.center(); 
      } 
     }); 
     image.setUrl(attachmentUrl + CFeedPostAttachment.ATTACHMENT_FILE); 
     Image.prefetch(attachmentUrl + CFeedPostAttachment.ATTACHMENT_FILE); 
    } 

然而,LoadEvent事件從來沒有發射,因此圖像永遠不會顯示。我該如何克服這一點?我想避免使用http://code.google.com/p/gwt-image-loader/,因爲如果我可以避免它,我不想添加額外的庫。謝謝。

回答

3

onLoad()方法只會在圖像加載到DOM後觸發。這是一個快速的解決方法:

... 

final Image image = new Image(attachmentUrl + CFeedPostAttachment.ATTACHMENT_FILE); 
image.addLoadHandler(new LoadHandler() { 
    @Override 
    public void onLoad(LoadEvent event) { 
     // since the image has been loaded, the dimensions are known 
     popupImage.center(); 
     // only now show the image 
     popupImage.setVisible(true); 
    } 
}); 

popupImage.add(image); 
// hide the image until it has been fetched 
popupImage.setVisible(false); 
// this causes the image to be loaded into the DOM 
popupImage.show(); 

... 

希望有所幫助。

+0

這真的很老,但只是想讓你知道這真的幫了我。我總是會遇到問題,讓負載監聽器能夠正常工作,這是唯一可以解決問題的解決方案。謝謝! – rjcarr 2015-12-31 21:05:16

+0

@rjcarr - 很高興幫助:)是的,這是很久以前。我不再與GWT一起工作xD – 2016-01-11 05:40:32