Southpaw Hare Southpaw Hare - 5 months ago 35
Java Question

Grid Layout - Sharing Relative Space

Is it possible to define manual ratios for columns in a grid layout which all grab excess horizontal space?

When using a Grid Layout with multiple items that have the grab excessive horizontal space option - particularly Tables, Trees, and the like - the layout automatically determines how to split the space between the multiple items based on various factors, such as how many columns each item has. This leads to the space being split unevenly between them, and this is intentional by design and usually a good thing.

30/70 Split

If one were to want the space to be split perfectly even, there is a make columns the same size option for that, as well.

50/50 Split

However, is it possible to define a different, non-automatic, non-equal-space percentage for columns? Would it be possible to, for instance, have the items in my examples have a 80/20 split with the larger amount going to the item with fewer columns, or which would otherwise be considered smaller through the automatic method?

Baz Baz

Very related to this answer:

Yes, it's possible, but it's not as easy as GridLayout#setWeight(col, weight). Unfortunately, you have to listen to Resize events of the Shell (or the container that holds your GridLayout) and then setting the GridData of the contained components. The code below will set the percentages to 75% and 25%:

public static void main(String[] args)
    Display display = Display.getDefault();
    final Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(2, false));

    Composite left = new Composite(shell, SWT.BORDER);
    Composite right = new Composite(shell, SWT.BORDER);

    final GridData leftData = new GridData(SWT.FILL, SWT.FILL, true, true);
    final GridData rightData = new GridData(SWT.FILL, SWT.FILL, true, true);


    shell.addListener(SWT.Resize, new Listener()
        public void handleEvent(Event arg0)
            Point size = shell.getSize();

            leftData.widthHint = (int) (size.x * 0.75);
            rightData.widthHint = size.x - leftData.widthHint;

            System.out.println(leftData.widthHint + " + " + rightData.widthHint + " = " + size.x);


    while (!shell.isDisposed())
        if (!display.readAndDispatch())

After starting:

enter image description here

After resizing:

enter image description here