Micha Wiedenmann
Micha Wiedenmann

Reputation: 20843

How to center a Button using a FormLayout in SWT?

How can I position a Button (vertically) at the center using a FormLayout (see here)? Using:

final Button button = new Button(shell, SWT.NONE);
button.setText("Button");

final FormData layoutData = new FormData();
layoutData.top = new FormAttachment(50);
layoutData.left = new FormAttachment(0);
layoutData.right = new FormAttachment(100);
button.setLayoutData(layoutData);

I end up with

enter image description here

Which is not surprising, since I told it to put the top of the button at the center (layoutData.top = new FormAttachment(50);). How can I instead put the center of the button at the center?

Upvotes: 1

Views: 1092

Answers (1)

Baz
Baz

Reputation: 36884

You can specify an offset with the constructor:

new FormAttachment(int numerator, int offset)

Looks like this:

enter image description here

You can compute the offset using:

final Button button = new Button(shell, SWT.NONE);
button.setText("Button");

final FormData layoutData = new FormData();

/* Compute the offset */
int offset = -button.computeSize(SWT.DEFAULT, SWT.DEFAULT).y / 2;

/* Create the FormAttachment */
layoutData.top = new FormAttachment(50, offset);
layoutData.left = new FormAttachment(0);
layoutData.right = new FormAttachment(100);
button.setLayoutData(layoutData);

Upvotes: 3

Related Questions