SWT文本组件不会水平填充

时间:2012-10-03 19:57:37

标签: java layout swt

我和SWT一起工作,我遇到了一些问题。基本上我有一个Text对象,我希望它的宽度是它所在组件的宽度。我可以使用FillLayout但是它下面的按钮也会增长,这不是我想要的。

这是一个用于说明问题的屏幕截图:
enter image description here

这是我用来重现的测试代码,并尝试解决问题:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;


public class Test {

    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);

        shell.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
        //setup the layout manager      
        GridLayout layout = new GridLayout(1, false);
        layout.horizontalSpacing = 0;
        layout.marginHeight = 0;
        layout.verticalSpacing = 5;
        layout.marginWidth = 0;
        layout.marginBottom = 20;
        layout.marginTop = 5;       

        shell.setLayout(layout);

        //create the text field
        Text inputField = new Text(shell, SWT.BORDER);
        GridData data =  new GridData();
        data.horizontalAlignment = GridData.FILL;
        data.grabExcessHorizontalSpace = true;
        inputField.setData(data);

        //create the button
        Button lookup = new Button(shell, SWT.PUSH);
        lookup.setText("Lookup");       


        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep();
        }
    }
}

我认为只是我没有在GridData的{​​{1}}对象上设置正确的东西,但不管它是什么我绝对不会看到它。

1 个答案:

答案 0 :(得分:6)

您必须使用setLayoutData()设置GridData而不是setData()

Text inputField = new Text(shell, SWT.BORDER);
GridData data =  new GridData();
data.horizontalAlignment = SWT.FILL;
data.grabExcessHorizontalSpace = true;
inputField.setLayoutData(data);

BTW:使用GridData.FILL is not recommended,改为使用SWT.FILL