Search code examples
swtgrid-layout

SWT gridlayout align


When put all widgets in one container, the gridlayout could align normally.
But for some reason, I need to put some widgets to a sub-container such as the composite as below. The alignment is different.

So the question is: Is there a container that has no effect on the gridlayout?
Ps: I know that can use white space as a workaround, but...

Code:

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    
    GridLayoutFactory.fillDefaults().numColumns(2).margins(8, 3).applyTo(shell);
    
    new Label(shell, 0).setText("Label1");
    new Text(shell, 0);
    
    new Label(shell, 0).setText("A long Label");
    new Text(shell, 0);
    
    Composite composite = new Composite(shell, 0);
    GridDataFactory.fillDefaults().span(2, 1).applyTo(composite);
    GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);

    new Label(composite, 0).setText("Label22");
    new Text(composite, 0);
    
    new Label(composite, 0).setText("Label223");
    new Text(composite, 0);
    
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

Result:
result


Solution

  • There is no container that can used like this. Sticking to a single composite is by far the easiest way to aligh the labels.

    It is possible to specify the widthHint of the GridData for a label to specify the width. You would have to calculate the width required using something like:

    List<Control> labels = ... list of Label controls 
    
    final int width = labels.stream()
       .mapToInt(label -> label.computeSize(SWT.DEFAULT, SWT.DEFAULT).x)
       .max()
       .getAsInt();
    
    final var labelData = GridDataFactory.swtDefaults().hint(width, SWT.DEFAULT);
    
    labels.forEach(labelData::applyTo);