如何在SWT中使用FormLayout使按钮居中?

时间:2013-07-17 14:59:15

标签: java swt

如何使用ButtonFormLayout(垂直)定位在中心(请参阅here)?使用:

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);

我最终得到了

enter image description here

这并不奇怪,因为我告诉它将按钮的顶部放在中间位置(layoutData.top = new FormAttachment(50);)。我怎样才能将按钮的中心放在中心?

1 个答案:

答案 0 :(得分:3)

您可以使用构造函数指定偏移量:

new FormAttachment(int numerator, int offset)

看起来像这样:

enter image description here

您可以使用以下方法计算偏移量:

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);