James Harpe
James Harpe

Reputation: 4345

SWT Grid Layout width

I'm trying to create a simple display using SWT. So far, I am successfully displaying information from my database and displaying it using a RowLayout, with each row containing a GridLayout. It looks like this:

enter image description here

What I really want is for the rows to extend to take up the full width of the window. How do I achieve this?

Thanks for your help!

Upvotes: 1

Views: 10619

Answers (1)

Baz
Baz

Reputation: 36884

The usual way to achieve this is to use GridData. This GridData tells the component how to behave within it's parent, e.g. how to spread across the parent.

By using:

component.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

you tell the component to occupy as much space as possible horizontally, but only the necessary space vertically.

Here is a small example that should behave in the way you expect it to:

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

        /* GridLayout for the Shell to make things easier */
        shell.setLayout(new GridLayout(1, false));

        for(int i = 0; i < 5; i++)
        {
            createRow(shell, i);
        }

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

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

    private static void createRow(Shell shell, int i)
    {
        /* GridLayout for the rows, two columns, equal column width */
        Composite row = new Composite(shell, SWT.NONE);
        row.setLayout(new GridLayout(2, true));

        /* Make each row expand horizontally but not vertically */
        row.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

        /* Create the content of the row, expand horizontally as well */
        Button first = new Button(row, SWT.PUSH);
        first.setText("FIRST " + i);
        first.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
        Button second = new Button(row, SWT.PUSH);
        second.setText("SECOND " + i);
        second.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
    }
}

This is what it looks like after startup:

enter image description here

and after resizing:

enter image description here


As a side note: I would suggest reading this tutorial from Eclipse about Layouts, if you haven't already read it. Every SWT developer should have read it.

Upvotes: 7

Related Questions