Sunil
Sunil

Reputation: 127

Centering a widget in DockLayoutPanel

I am trying to place a widget (composite) within a DockLayoutPanel, i want this to be at center (vertical as wellas horizontal) . Not using uibinder . How to do it?

Upvotes: 0

Views: 3649

Answers (2)

LINEMAN78
LINEMAN78

Reputation: 2562

The problem is that unless you make assumptions that the window will not be resized it is not possible to solve this problem in a LayoutPanel without a WindowResizeHandler, however it can easily be solved with a table.

DockLayoutPanel dockLayoutPanel = new DockLayoutPanel(Unit.EM);
// some code here
Button button = new Button("center");
FlexTable wrapper = new FlexTable();
wrapper.setSize("100%", "100%");
wrapper.setWidget(0, 0, button);
wrapper.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE);
wrapper.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
dockLayoutPanel.add(wrapper);

Upvotes: 0

Jason Terk
Jason Terk

Reputation: 6025

Note that the UIBinder notation of "center" when laying out a DockLayoutPanel does not refer to the widget being physically centered in the panel but to the center widget taking up all space in the containing panel not used by those widgets added to the sides. I.e. in the following layout the widget C is the "center" panel even though it flows all the way to the right of its container.

<g:DockLayoutPanel>
  <g:north><g:Label>A</g:Label></g:north>
  <g:west><g:Label>B</g:Label></g:north>
  <g:center><g:Label>C</g:Label></g:center>
  <g:south><g:Label>D</g:Label></g:south>
</g:DockLayoutPanel>

----------------
|      A       |
----------------
|B|    C       |
----------------
|      D       |
----------------

If you were to add a single child "center" widget to a DockLayoutPanel it would use up all vertical and horizontal space in the panel - it would not be centered.

If you want to achieve physical centering using one of the absolute positioning layout panels I suggest just using LayoutPanel:

LayoutPanel panel = new LayoutPanel();
MyWidget myWidget = new MyWidget();
panel.add(myWidget);

// Note that this assumes that both widgets are attached and have meaningful
// sizes - use the RequiresResize interface to get notification of when the
// positioning of myWidget needs change. Note also that if panel or myWidget
// have any decoration that modifies its offsetWidth (margin, border, padding)
// that will need to be taken into account to correctly center myWidget.
int top = panel.getOffsetHeight() - (myWidget.getOffsetHeight() / 2);
int left = panel.getOffsetWidth() - (myWidget.getOffsetWidth() / 2);
panel.setWidgetTopHeight(myWidget, top, Unit.PX, myWidget.getOffsetHeight(), Unit.PX);
panel.setWidgetLeftWidth(myWidget, left, Unit.PX, myWidget.getOffsetWidth(), Unit.px);

Upvotes: 1

Related Questions