How to right align buttons on a HorizontalPanel (GWT)

Viewed 52733

I am trying to implement a simple dialog. I would like to have OK and cancel buttons aligned right at the bottom of the dialog. I embed the buttons into the HorizontalPanel and try to set horizontal alignment to RIGHT. However, this does not work. How to make the buttons align right? Thank you. Here's the snippet:

private Widget createButtonsPanel() {
    HorizontalPanel hp = new HorizontalPanel();
    hp.setCellHorizontalAlignment(saveButton, HasHorizontalAlignment.ALIGN_RIGHT);
    hp.setCellHorizontalAlignment(cancelButton, HasHorizontalAlignment.ALIGN_RIGHT);
    hp.add(saveButton);
    hp.add(cancelButton);       

    return hp;
}
10 Answers

The point is to call setHorizontalAlignment before adding your buttons as shown below:

final HorizontalPanel hp = new HorizontalPanel();
final Button saveButton = new Button("save");
final Button cancelButton = new Button("cancel");

// just to see the bounds of the HorizontalPanel
hp.setWidth("600px");
hp.setBorderWidth(2);

// It only applies to widgets added after this property is set.
hp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);

hp.add(saveButton);
hp.add(cancelButton);

RootPanel.get().add(hp);

If you want your buttons to be tight together - put them both into some new container, and them put the container inside the right-alighned HorizontalPanel

You might want to use Firebug to checkout the extents of the HorizontalPanel itself. You might need a

hp.setWidth("100%");

The HorizontalPanel generally sizes itself to the contents, so if you put a couple of buttons in it it will be left aligned as the table itself does not expand.

You could also use setCellHorizontalAlignment on the panel that contains the HorizontalPanel. That's what I do.

// doesn't necessarily have to be a vertical panel
VerticalPanel container = new VerticalPanel();
HorizontalPanel buttons = new HorizontalPanel();
// add the buttons
container.add(buttons);
container.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_RIGHT);

Try to add the buttons first and then call hp.setHorizontalAlignment("your aligment here").

Good luck!

Related