0

I can't get the actual dimensions of an object when it is first created and laid out by the LayoutPanel. I am using LayoutPanel to size a widget by percentage:

MyClass displayObject = new MyClass();
add(displayObject);
setWidgetLeftWidth(displayObject, 0.0, Unit.PCT, 15.0, Unit.PCT);
setWidgetTopHeight(displayObject, 0.0, Unit.PCT, 30.0, Unit.PCT); 

In the class I override onResize():

public MyClass extends AbsolutePanel implements RequiresResize {

@Override
public void onResize() {
Integer maxWidth = getOffsetWidth();
Integer maxHeight = getOffsetHeight();    

// ... need to use maxWidth here...     
}
}

My problem is that onResize() is not called unless the browser is physically resized, and I need the correct dimensions when the object is first displayed.

If I call forceLayout(), it creates a call to onResize(), but getOffsetWidth() returns zero. I need to force a call to onResize() that executes AFTER the object has been laid out.

1 Answers1

0

You should give browser a little time to complete the layout before asking for a size:

Scheduler.get().scheduleDeferred(new ScheduledCommand() {

    @Override
    public void execute() {
        Integer maxWidth = getOffsetWidth();
        Integer maxHeight = getOffsetHeight(); 
        // etc.
    }
});

You can read more here: GWT: Timer and Scheduler Classes

Community
  • 1
  • 1
Andrei Volgin
  • 40,755
  • 6
  • 49
  • 58
  • This solution works. However, there are some subtleties worth understanding. The reason I'm using onResize() is because LayoutPanels do not scale images, you have to do that manually. I have some images I'm loading into offscreen objects, and later bringing into view. For those objects, when they are first created, inside scheduleDeferred() the getOffsetWidth() function returns 0. Later, when the animation is complete and the object has been brought into view, the browser calls scheduleDeferred() again, and this time getOffsetWidth() returns a valid width. – Greg Watkins Aug 01 '14 at 20:04
  • If you can resize your images using CSS, it will be more efficient. – Andrei Volgin Aug 01 '14 at 20:56