Durgesh Sahu Durgesh Sahu - 21 days ago 6
Java Question

How can we auto resize the size of components in SWT?

In my SWT application i have certain components inside the SWT shell.

Now how can i auto re-size this components according to the size of display window.

Display display = new Display();

Shell shell = new Shell(display);
Group outerGroup,lowerGroup;
Text text;

public test1() {
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns=1;
shell.setLayout(gridLayout);

outerGroup = new Group(shell, SWT.NONE);

GridData data = new GridData(1000,400);
data.verticalSpan = 2;
outerGroup.setLayoutData(data);

gridLayout = new GridLayout();

gridLayout.numColumns=2;
gridLayout.makeColumnsEqualWidth=true;
outerGroup.setLayout(gridLayout);

...
}


i.e when I decrease the size of window the components inside it should appear according to that.

Baz Baz
Answer

That sounds suspiciously like you aren't using layouts.

The whole concept of layouts makes worrying about resizing needless. The layout will take care of the size of all of its components.

I would recommend to read the Eclipse article about layouts

Your code can easily be corrected. Don't set the size of individual components, the layout will determine their size. If you want the window to have a predefined size, set the shell's size:

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

    Group outerGroup = new Group(shell, SWT.NONE);

    // Tell the group to stretch in all directions
    outerGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    outerGroup.setLayout(new GridLayout(2, true));
    outerGroup.setText("Group");

    Button left = new Button(outerGroup, SWT.PUSH);
    left.setText("Left");

    // Tell the button to stretch in all directions
    left.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    Button right = new Button(outerGroup, SWT.PUSH);
    right.setText("Right");

    // Tell the button to stretch in all directions
    right.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    shell.setSize(1000,400);
    shell.open();

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

Before resizing:

Before resizing

After resizing:

After resizing