在居中的PopupPanel onLoad中显示GWT图像

时间:2011-03-10 10:10:35

标签: java gwt onload-event

使用GWT我正在使用ClickHandler显示图像缩略图,然后在居中的PopupPanel中显示完整图像(可以是几MB)。为了使其居中,必须在显示弹出窗口之前加载图像,否则图像的左上角放置在屏幕的中间(图像认为它是1px大)。这是我用来执行此操作的代码:

    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/,因为如果我可以完全避免使用它,我不想添加额外的库。感谢。

1 个答案:

答案 0 :(得分: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();

 ...

希望有所帮助。