GridData 必须应用于Texts,而不是它们的父级。所以你必须“触摸”它们:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell();
shell.setText("StackOverflow");
shell.setLayout(new GridLayout(2, false));
new Label(shell, SWT.NONE).setText("name");
Text name = new Text(shell, SWT.BORDER);
name.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
new Label(shell, SWT.NONE).setText("memory");
Text memory = new Text(shell, SWT.BORDER);
memory.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
new Label(shell, SWT.NONE).setText("processors");
Text processors = new Text(shell, SWT.BORDER);
processors.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
看起来像这样:
更新
好的,再次考虑您的要求,并提出了另一个解决方案。在此解决方案中,您不必引用实际的 Text 对象,但您将搜索它们:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell();
shell.setText("StackOverflow");
shell.setLayout(new GridLayout(2, false));
new Label(shell, SWT.NONE).setText("name");
new Text(shell, SWT.BORDER);
new Label(shell, SWT.NONE).setText("memory");
new Text(shell, SWT.BORDER);
new Label(shell, SWT.NONE).setText("processors");
new Text(shell, SWT.BORDER);
applyGridData(shell);
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
private static void applyGridData(Control parent)
{
if(parent instanceof Text)
{
parent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
}
else if(parent instanceof Composite)
{
Composite comp = (Composite) parent;
for(Control control : comp.getChildren())
applyGridData(control);
}
}
基本上,此解决方案在您的Composite 中递归搜索Text 对象,然后将GridData 应用于它们。