Jacob Schoen
Jacob Schoen

Reputation: 14192

SWT Text Component will not fill Horizontally

I working with SWT and am having some issues laying things out the way I want. Essentially I have a Text object that I want to have its width be what ever the width of the component it is located in is. I could use FillLayout but then the button below it would also grow, which is not what I want.

Here is a screen shot to illustrate the problem:
enter image description here

Here is a the test code I am using to reproduce, and try to fix the problem:

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

I assume it is just I am not setting something correctly on the GridData object for the inputField, but whatever it is I am definitely not seeing it.

Upvotes: 0

Views: 4548

Answers (1)

Baz
Baz

Reputation: 36884

You have to use setLayoutData() to set the GridData not setData():

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

BTW: the use of GridData.FILL is not recommended, use SWT.FILL instead.

Upvotes: 6

Related Questions